按键名称汇总所有对象

时间:2018-06-12 10:41:07

标签: javascript arrays loops object

我希望使用循环按键名称对所有对象求和。关键" id"将被删除

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:...
          }
        });

我喜欢这个结果

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

1 个答案:

答案 0 :(得分:0)

如果你遍历里面 reduce函数中的所有键并将它们添加到结果中,那么输入对象可以拥有它,而不是硬编码键。任意键/数字对:

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);