Skip to content
Advertisement

How could I sum a property of each object for separate object arrays?

I had an object which in it had objects which each had an array of objects with 0..n objects. The main object looked something like this:

{
    obj1: [{obj1.1}, {obj1.2}, {obj1.3}],
    obj2: [{obj2.1}]
    obj3: [{obj3.1}, {obj3.2}]
}

Each object (obj1, obj2 and obj3) held a group of common objects in an array of objects. E.g. obj1 has a group of objects in an object array (obj1.1, obj1.2 and obj1.3) all which have a common property that groups them together.

I want to now be able to iterate over each object separately in each object array in order to sum a particular property (which each object has) for each object array.

I have used Object.keys to iterate over each object array, although I still am unable to get a separate summed value per object array.

For example:

{
    obj1: [
       0: { price: 10 }
       1: { price: 10 }
       2: { price: 10 }
    ],
    obj2: [
       0: { price: 10 }
    ],
    obj3: [
       0: { price: 10 }
       1: { price: 10 }
    ]
}

I want to be able to sum the property price for each individual object array. Therefore for obj1 I should have a summed amount of 30. For obj2 I should have a summed amount of 10, and lastly for obj3 I should have a summed amount of 20.

I can iterate over each object array using Object.keys, however as it stands now, when iterating over each individual element in each object array (using a foreach), I am only summing a final amount for all objects in all three object arrays. I.e. I am getting a summed amount of 60.

var total = 0;
for (var key of Object.keys(result)) {
    result[key].forEach(element => {
        total += element.Price;
    });
};
console.log(total);

What could I use to get the three individually summed amounts per object array?

Advertisement

Answer

function sum(prices)
{
  let total = 0;
  prices.forEach((entry) => total += entry.price);
  return total;
}

console.log(sum(obj1));
console.log(sum(obj2));
console.log(sum(obj3));

Why was this hard again? You had the right code, just needed to break things out.

Advertisement