Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you merge objects in array of objects?

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?

like image 382
Rafonix Avatar asked Oct 11 '18 13:10

Rafonix


People also ask

How do I merge an array of objects into one?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How do I combine two arrays of objects?

To combine two arrays into an array of objects, use map() from JavaScript.

How can we merge two objects?

To merge two objects in JavaScript, you can use the spread ... operator. The spread operator creates a new object with all the properties from the first and second object. If there's two properties with the same name, the property from the second object wins out.

How do you merge two objects in react?

How do you merge two objects in react JS? To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ) Use the Object. assign() method.


1 Answers

You could reduce the array by iterating the entries and collecting the values, depending of the keys.

const
    array = [{ name: 'Fred', surname: 'Shultz' }, { name: 'Anne', surname: 'Example' }],
    result = array.reduce((r, o) => {
        Object.entries(o).forEach(([k, v]) => (r[k] = r[k] || []).push(v));
        return r;
    }, Object.create(null));

console.log(result);
like image 154
Nina Scholz Avatar answered Sep 19 '22 06:09

Nina Scholz