I am trying to compute multiple sums from an array of objects:
[{value1: 3, value2:6}, {value1: 2, value2: 4},...].
Potentially, the object can contain an unspecified number of keys (i.e. value1:, value2:, value3:..., value n).
Based on this example, the sum of all the value1 keys should return 5 while the sum of all the value2 keys should return 10.
What I did so far is as follows:
let sum = 0;
const myArrayObject = [{value1: 3, value2:6}, {value1: 2, value2: 4}];
const objectKeys = Object.keys(myArrayObject[0]); //Gives me the keys of the object
objectKeys.forEach(key => {
myArrayObject.map((entry) => {
sum += entry[key];
});
});
return sum;
This however gives me the total 15. Is there a way to actually compute the sum for all the value1 keys and value2 keys separately?