1

I'd like to Sum all objects by their key name using loop. The key "id" will be delete

var arr = [{id:1, "my color":1,"my fruit":4},{id:2,"my color":2,"my fruit":4},etc];

var merged = arr.reduce(function(previousValue, currentValue) {
     return {
            "my fruit": previousValue["my fruit"] + currentValue["my fruit"],
            "my color": previousValue["my color"] + currentValue["my color"],
             etc:...
          }
        });

I'd like this result

result = [{"my color":3},{"my fruit":8},etc];
observatoire
  • 167
  • 8

1 Answers1

0

Rather than hard-coding the keys, it would be more flexible if you iterated over all keys in the object inside the reduce function and add them to the result, that way the input objects can have arbitrary key/number pairs:

const arr = [{id:1, "my color":1,"my fruit":4},{id:2,"my color":2,"my fruit":4}];
const res = arr.reduce((a, { id, ...rest }) => {
  Object.entries(rest).forEach(([key, val]) => {
    a[key] = (a[key] || 0) + val;
  });
  return a;
}, {});
console.log(res);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320