I have an array of objects that I want to iterate through and sum some values if the keys exist in the sumList array and average all others. How can we best achieve this?
let sumList = ['TEST1', 'TEST2']
data.forEach(item => {
Object.keys(item).forEach(key => {
if (!result.hasOwnProperty(key)) {
result[key] = 0;
}
if(sumList.includes(key)) {
result[key] += item[key]
} else {
result[key] = (result[key] + item[key]) / 2;
}
});
});
The bug i am running into, i think has to do with the fact that initially value is 0... and it tried to divide 0 + the next value by 2. I would like to do this in the same loop insteam of first summing them then running another loop and averaging them.