Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change multiple array becomes array with object?

I try to use forEach and push a new array to achieve it, but the result is wrong.

const dummyArray = [
  [45292, 1, 2],
  [46292, 5, 6],
  [47292, 9, 10],
]

const resultArray: any[] = []

dummyArray.forEach((elementValue, index) => {
  resultArray.push({ date: '', price: '', code: '' })

  elementValue.forEach(value => {
    if (index === 0) {
      resultArray[index] = { ...resultArray[index], date: value }
    }
    if (index === 1) {
      resultArray[index] = { ...resultArray[index], price: value }
    }
    if (index === 2) {
      resultArray[index] = { ...resultArray[index], code: value }
    }
  })
})

console.log('resultArray', resultArray)

the result becomes

[
  { date: 2, price: '', code: ''},
  { date: '', price: 6, code: ''},
  { date: '', price: '', code: 10},
]

I want it becomes like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  { date: 45292, price: 1, code: 2},
  { date: 46292, price: 5, code: 6},
  { date: 47292, price: 9, code: 10},
]

How do I achieve it ?

>Solution :

You need a different index for your if condition (subIndex):

dummyArray.forEach((elementValue, index) => {
  resultArray.push({ date: "", price: "", code: "" });

  elementValue.forEach((value, subIndex) => {
    if (subIndex === 0) {
      resultArray[index] = { ...resultArray[index], date: value };
    }
    if (subIndex === 1) {
      resultArray[index] = { ...resultArray[index], price: value };
    }
    if (subIndex === 2) {
      resultArray[index] = { ...resultArray[index], code: value };
    }
  });
});

You could also do below.

const keyArray = ["date", "price", "code"];

dummyArray.forEach((elementValue, index) => {
  elementValue.forEach((value, subIndex) => {
    resultArray[index] = { ...resultArray[index], [keyArray[subIndex]]: value };
  });
});

Or:

const dummyArray = [
  [45292, 1, 2],
  [46292, 5, 6],
  [47292, 9, 10],
];
const keyArray = ["date", "price", "code"];

const resultArray = dummyArray.map((elementValue) =>
  elementValue.reduce((acc, value, subIndex) => {
    return { ...acc, [keyArray[subIndex]]: value };
  }, {})
);

console.log("resultArray", resultArray);

Note that, using reduce should come with a return inside reduce.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading