Combine array of objects in JavaScript


Suppose, we have an array of objects that contains data about some students like this −

const arr = [{
   name: 'A',
   idNo: 1,
   marks: {
      math: 98,
      sci: 97,
      eng: 89
   }
},
{
   name: 'B',
   idNo: 2,
   marks: {
      math: 88,
      sci: 87,
      eng: 79
   }
},
{
   name: 'C',
   idNo: 3,
   marks: {
      math: 87,
      sci: 98,
      eng: 91
   }
}];

We are required to write a JavaScript function that takes in one such array.

Our function should then prepare an object of properties, one property for each object id the objects currently have.

Therefore, for the above array, the output should look like −

const output = {
   name: [A, B, C],
   idNo: [1, 2, 3],
   marks: [{
      math: 98,
      sci: 97,
      eng: 89
   },
   {
      math: 88,
      sci: 87,
      eng: 79
   },
   {
      math: 87,
      sci: 98,
      eng: 91
   }]
};

Example

The code for this will be −

const arr = [{
   name: 'A',
   idNo: 1,
   marks: {
      math: 98,
      sci: 97,
      eng: 89
   }
},
{
   name: 'B',
   idNo: 2,
   marks: {
      math: 88,
      sci: 87,
      eng: 79
   }
},
{
   name: 'C',
   idNo: 3,
   marks: {
      math: 87,
      sci: 98,
      eng: 91
   }
}];
const combineMarks = (arr = []) => {
   let res = [];
   res = arr.reduce((acc, val) => {
      Object.keys(val).forEach(el => {
         if (!acc[el]) {
            acc[el] = [];
         };
         acc[el].push(val[el])
      });
      return acc;
   }, {});
   return res;
};
console.log(combineMarks(arr));

Output

And the output in the console will be −

{
   name: [ 'A', 'B', 'C' ],
   idNo: [ 1, 2, 3 ],
   marks: [
      { math: 98, sci: 97, eng: 89 },
      { math: 88, sci: 87, eng: 79 },
      { math: 87, sci: 98, eng: 91 }
   ]
}

Updated on: 23-Nov-2020

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements