I have below kind of kind of array of object data which contain nested array of object inside it, and I want to structure it based on what my Api needed.
[{
containerId: 'c12',
containerNumber: '4321dkjkfdj',
goods: [{
weight: '32kg',
quantity: '3'
}]
},
{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{
weight: '322kg',
quantity: '32'
}]
},
{
containerId: 'c13',
containerNumber: '1212dkjkfdj',
goods: [{
weight: '13kg',
quantity: '3'
}]
},
{containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{
weight: '13kg',
quantity: '3'
}]
},
]
and I want to have an Object with same 'containerId' as a one object by including the 'goods' property that has the same 'containerId' like the below code:
[{
containerId: 'c12',
containerNumber: '4321dkjkfdj',
goods: [{
weight: '32kg',
quantity: '3'
},
{
weight: '322kg',
quantity: '32'
}
]
},
{
containerId: 'c13',
containerNumber: '1212dkjkfdj',
goods: [{
weight: '13kg',
quantity: '3'
},
{
weight: '13kg',
quantity: '3'
}
]
}
]
CodePudding user response:
You can iterate through the items and build a lookup object by using .reduce()
, where the key is containerId
and values are {containerId, containerNumber, goods}
. If a key is found in accumulator a[containerId]
we just need to update goods
.
const arr = [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ weight: '32kg', quantity: '3' }] }, { containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ weight: '322kg', quantity: '32' }] }, { containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{ weight: '13kg', quantity: '3' }] }, { containerId: 'c13', containerNumber: '1212dkjkfdj', goods: [{ weight: '13kg', quantity: '3' }] } ]
const res = arr.reduce((a,{containerId, containerNumber, goods}) => ((a[containerId] ??= {containerId, containerNumber, goods: []}).goods = [...a[containerId].goods, ...goods],a), {});
console.log(Object.values(res));
.as-console-wrapper { max-height: 100% !important }
CodePudding user response:
const a = [
{
containerId: 'c12',
containerNumber: '4321dkjkfdj',
goods: [{
weight: '32kg',
quantity: '3'
}]
},
{
containerId: 'c12',
containerNumber: '4321dkjkfdj',
goods: [{
weight: '322kg',
quantity: '32'
}]
},
{
containerId: 'c13',
containerNumber: '1212dkjkfdj',
goods: [{
weight: '13kg',
quantity: '3'
}]
},
{
containerId: 'c13',
containerNumber: '1212dkjkfdj',
goods: [{
weight: '13kg',
quantity: '3'
}]
}
]
const result = a.reduce((p, c) => {
const found = p.findIndex(p => p.containerId === c.containerId);
found === -1 ? p.push(c) : p[found].goods.push(c.goods);
return p
}, []);
console.log(result);