I have been stuck on this for 8 days now.
Let's say here is my response object array:
var items = [
{
name: 'dell-66',
price: 200,
id: 12,
},
{
name: 'hp-44',
price: 100,
id: 10,
},
{
name: 'acer-33',
price: 250,
id: 33,
},
{
name: 'dell-66',
price: 200,
id: 12,
},
{
name: 'acer-33',
price: 250,
id: 33,
},
{
name: 'dell-66',
price: 200,
id: 12,
},
]
So far i have managed to make a function using reduce to accumulate the price. Here is the code that does this:
var obj = items.reduce( function (allItems, currentItem) {
var item_name = currentItem.name;
var item_price = currentItem.price;
var total_prices = allItems[item_price] = (allItems[item_price] || 0) +
item_price;
var result = {};
result[item_name] = {
item_price: total_prices,
}
return Object.assign(allItems, result);
}, {} )
Although this works, it does not return the results i want, instead it returns this:
{
'100': 100,
'200': 600,
'250': 500,
'dell-66': { item_price: 600 },
'hp-44': { item_price: 100 },
'acer-33': { item_price: 500 }
}
Here is what i intended and need it to be (without the extra key/values at the top):
{
'dell-66': { item_price: 600 },
'hp-44': { item_price: 100 },
'acer-33': { item_price: 500 }
}
How Can i achieve this please?