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?
easy with lodash:
pure es6
if the keys differ from item to item, you could use something like this to collect them all:
The following should work - uses a few ES6 helpers, but the key is
Array#reduce
which is in ES5.If the
arrayOfObjects
is set on these 2 props then it is as simple as:One
reduce
with an accumulator of{name:[], surname:[]}
to be filled.If you need to be more generic and work for
any set of objects
:Again is just a
reduce
withObject.keys
to do the job.Note both approaches utilize ES6 arrow functions, array destricturing and (for the 2nd one) combining multiple operations via enclosing them in parentheses
(op1,op2)
You could reduce the array by iterating the entries and collecting the values, depending of the keys.
This is one abroach of implementation details, written in fairly easy to understand and readable manner.
https://codesandbox.io/s/r7x16j950n
You can use lodash's
mergeWith
like so:Example: