How can you merge objects in array of objects?

  • A+
Category:Languages

I'm looking for the best solution to merge all objects in one array

const arrayOfObjects = [  {name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'} ]; 

I want to achieve: {name: ['Fred', 'Anne'], surname: ['Example', 'Shultz']}

What's the best option for that (es6)? Maybe I can do something like that using lodash? Which helpers should I use?

 


You could do it like this:

const arrayOfObjects = [   {name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'} ];  const result = {}; arrayOfObjects.forEach(item => {   Object.keys(item).forEach(key => {     if (!result[key]) {       result[key] = [];     }     result[key].push(item[key]);   }); });  console.log(result);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: