I have an array of arrays, of the same size, of objects like this:
const array = [
[{ name: 'John' }, { name: 'Julie' }, { name: 'Zack' }],
[{ color: 'blue' }, { color: 'orange' }, { color: 'green' }],
[{ age: 12 }, { age: 10 }, { age: 35 }]
];
How do I merge these arrays object by object to have an output like this?
const result = [{ name: 'John', color: 'blue', age: 12 }, { name: 'Julie', color: 'orange', age: 10 } ...]
If it could be using lodash, it would be nice too. Thanks in advance
assign() method to convert an array of objects to a single object. This merges each object into a single resultant object. The Object. assign() method also merges the properties of one or more objects into a single object.
Use the spread syntax (...) to merge arrays in React, e.g. const arr3 = [...arr1, ...arr2] . The spread syntax is used to unpack the values of two or more arrays into a new array. The same approach can be used to merge two or more arrays when setting the state. Copied!
In order to merge two arrays, we find its length and stored in fal and sal variable respectively. After that, we create a new integer array result which stores the sum of length of both arrays. Now, copy each elements of both arrays to the result array by using arraycopy() function.
To combine two or more arrays, you can either use the functional method []. concat(arr1, arr2) or the spread operator [...arr1,...arr2]. The merging outcome is kept in a new array, making these methods immutable.
You can use map
and destructuring
const array1 = [{ name: 'John' }, { name: 'Julie' }, { name: 'Zack' }];
const array2 = [{ color: 'blue' }, { color: 'orange' }, { color: 'green' }];
const array3 = [{ age: 12 }, { age: 10 }, { age: 35 }];
let final = array1.map((a, i) => ({ ...a,
...array2[i],
...array3[i]
}))
console.log(final)
But would it work with several arrays?
const array = [
[{ name: 'John' }, { name: 'Julie' }, { name: 'Zack' }],
[{ color: 'blue' }, { color: 'orange' }, { color: 'green' }],
[{ age: 12 }, { age: 10 }, { age: 35 }],
[{ someProp: 1 }, { someProp: 2 }, { someProp: 3 }]
];
let remaining = array.slice(1,)
let final = array[0].map((v,i)=>{
let temp = {...v}
remaining.forEach(v2=>{
temp = {...temp, ...v2[i]}
})
return temp
})
console.log(final)
A caveman approach - pushing to an array from a for-loop.
const array1 = [{ name: 'John' }, { name: 'Julie' }, { name: 'Zack' }];
const array2 = [{ color: 'blue' }, { color: 'orange' }, { color: 'green' }];
const array3 = [{ age: 12 }, { age: 10 }, { age: 35 }];
let result = [];
for ( let i = 0; i < array1.length; i++ ){
result.push( { ...array1[i], ...array2[i], ...array3[i] } );
}
console.log( result );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With