For the following array :
const a = [
{
26: [0],
27: [100],
28: [0]
},
{
26: [0],
27: [100],
28: [0]
},
{
26: [0],
27: [100],
28: [0]
}
]
I need a function that should merge arrays with the same keys in the object.
`const result = [{
26: [0,0,0],
27: [100,100,100],
28: [0,0,0]
}]`
Advertisement
Answer
Try to use reduce
const data = [{
26: [0], 27: [100], 28: [0]
},
{
26: [0], 27: [100], 28: [0]
},
{
26: [0], 27: [100], 28: [0]
}
];
const restructure = arr =>
[arr.reduce((accumu, current) => {
for (const [key, val] of Object.entries(current)) {
accumu[key] = [...accumu[key] ?? '', ...val];
}
return accumu;
}, {})];
console.log(JSON.stringify(restructure(data)));