I have an array of objects -
[{
title: "oranges",
id: 5802537,
cart: {
purchased: 3,
stockTotal: 9
},
price: 3,
department: "fresh fruit and veg"
},
{
title: "pasta",
id: 5802537,
cart: {
purchased: 2,
stockTotal: 15
},
price: 1,
department: "dry goods"
},
{
title: "eggs",
id: 5802537,
cart: {
purchased: 1,
stockTotal: 11
},
price: 2,
department: "baking"
}
]
I am trying to write a function that will get add up all the stockTotal and purchased from each object. I have tried this -
let val = items.reduce(function(previousValue, currentValue) {
return {
purchased: previousValue.cart.purchased + currentValue.cart.purchased,
stockTotal: previousValue.cart.stockTotal + currentValue.cart.stockTotal
};
});
console.log(val);
However, it says that it cannot read property 'purchased' of undefined and cannot read property 'stockTotal' of undefined. I am wondering if this is because stockTotal and purchased are in their own object within each object in the array?