I'm stucked and need help. I have an object and need to merge objects by name and sum their counts.
products = {
fruit: [
{ name: orange, count: 1 },
{ name: orange, count: 2 },
{ name: apple, count: 3 },
{ name: apple, count: 2 },
],
vegetables: [
{ name: tomato, count: 3 },
{ name: tomato, count: 4 },
{ name: onion, count: 1 },
{ name: onion, count: 3 },
]
}
Final goal is to get object like this
products = {
fruit: [
{ name: orange, count: 3 },
{ name: apple, count: 5 },
],
vegetables: [
{ name: tomato, count: 7 },
{ name: onion, count: 4 },
]
}
Using for in loop I got into products object. I tried with reduce function but didn't succeed. Also I tried with [... new Set()] and I managed to merge objects by name, but counts didn't sum their values.
let temp = {}
for(let category in products){
const product = products[category]
temp = product.reduce((acc, curr) => {
if(acc.name === curr.name){
return{
name: acc.name,
count: acc.count + curr.count
}
}
}, {})
}