0

I have an array as follows:

var data = [
  {code: '1', name: 'aa'},
  {code: '20', name: 'bb'},
  {code: '30', name: 'cc'},
  {code: '123', name: 'dd'}
]

I expect the new array to look like this:

 var newData = [
  {status: '1', code: '1', name: 'aa'},
  {status: '2', list: [
    {code: '20', name: 'bb'},
    {code: '30', name: 'cc'}
  ]},
  {status: '3', code: '123', name: 'dd'}
]
console.log(newData)

I tried to use a for loop, but the code is quite repetitive:

var temp = []
var list = []
for(var item in data){
 if (data[item].code === '1') {
  temp.push({
    status: '1',
    code: data[item].code,
    name: data[item].name
  })
 }
 if (data[item].code === '20' || data[item].code === '30') {
  list.push(data[item])
  temp.push({
    status: '2',
    list: list
  })
 }
 if (data[item].code === '123') {
  temp.push({
    status: '3',
    code: data[item].code,
    name: data[item].name
  })
 }
}
3
  • 1
    Where does the status property come from? Are you really supposed to hard-code it for 1, 20 / 30, and 123? Commented Nov 6, 2019 at 3:07
  • @CertainPerformance Yes, they are fixed values Commented Nov 6, 2019 at 3:12
  • You have a list variable which is not get cleared after iteration. That will be already carrying data for previous iteration in for loop. Commented Nov 6, 2019 at 3:27

1 Answer 1

4

First create a mapping of each code to its associated status. Then iterate over the data, inserting into a new object indexed by status. If something at that status doesn't exist in the new object yet, create an object with a code property - otherwise, if it exists with a code property, turn it into an array, and push to that array.

At the end, take the values of the new object to turn it into the desired array format:

const statusByCode = {
  1: 1,
  20: 2,
  30: 2,
  123: 3,
}

var data = [
  {code: '1', name: 'aa'},
  {code: '20', name: 'bb'},
  {code: '30', name: 'cc'},
  {code: '123', name: 'dd'}
];
const dataByStatus = {};
for (const { code, name } of data) {
  const status = statusByCode[code];
  if (!dataByStatus[status]) {
    dataByStatus[status] = { status, code, name };
  } else {
    if (dataByStatus[status].code) {
      const { status: _, ...oldObj } = dataByStatus[status];
      dataByStatus[status] = { status, list: [oldObj] };
    }
    dataByStatus[status].list.push({ code, name });
  }
}

const output = Object.values(dataByStatus);
console.log(output);

Sign up to request clarification or add additional context in comments.

1 Comment

I understand! Thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.