I\'m looking for the best solution to merge all objects in one array
const arrayOfObjects = [
{name: \'Fred\', surname: \'Shultz\'}, {name: \'Anne\', surnam
If the arrayOfObjects is set on these 2 props then it is as simple as:
const data = [{ name: 'Fred', surname: 'Shultz' }, { name: 'Anne', surname: 'Example' }]
const r = data.reduce((r,c) =>
(r.name.push(c.name), r.surname.push(c.surname),r), {name:[], surname:[]})
console.log(r)
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:
const data = [{
name: 'Fred',
surname: 'Shultz'
},{
name: 'Anne',
surname: 'Example'
},{
name: 'John',
position: 'Dev' // <--- Notice different prop
}]
const result = data.reduce((r,c) =>
(Object.keys(c).map(k => r[k] = [...r[k] || [], c[k]]), r), {})
console.log(result)
Again is just a reduce with Object.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)