My goal is from an array object like this:
const data = [
{
code: 'prod1',
quantity: 13,
pricePerItem: 10,
totalCost: 130
},
{
code: 'prod1',
quantity: 7,
pricePerItem: 11,
totalCost: 77
},
{
code: 'prod2',
quantity: 10,
pricePerItem: 9,
totalCost: 90
},
{
code: 'prod2',
quantity: 9,
pricePerItem: 10,
totalCost: 90
},
];
build an object with code as key an object with aggregation data like:
{
prod1:{
quantity: 20,
total: 207
},
prod2:{
quantity: 19,
total:180
}
}
Without the object keys is quite easy
data.reduce(
(acc, current) => {
return {
total: acc.total + current.totalCost,
quantity: acc.quantity + current.quantity
};
},
{ total: 0, quantity: 0 }
);
but with the object keys I'm stuck Could you help me, please?