What is the best way to merge array contents from JavaScript objects sharing a key in common?
How can array in the example below be reorganized into output? Here, all value keys (whether an array or not) are merged into all objects sharing the same name key.
const array =
[
{
brand: ['Adidas', 'Nike']
color: ['red']
},
{
brand: ['Puma', 'Nike'],
size: ['31', '32']
}
]
/* Expect output
[{
brand: ['Adidas', 'Puma', 'Nike'],
size: ['31', '32']
color: ['red']
}]
*/
>Solution :
This should work
const array =
[
{
brand: ['Adidas', 'Nike'],
color: ['red']
},
{
brand: ['Puma', 'Nike'],
size: ['31', '32']
}
]
const res = array.reduce((prev, curr) => {
for(let key in curr) {
if(!prev[key]) {
prev[key] = curr[key]
} else {
prev[key].push(...curr[key])
}
}
return prev
}, {})
console.log(res)