使用 Underscore 或 Lodash 将行数组缩减为聚合汇总行

Reducing an array of rows to an aggregate summed-up row using Underscore or Lodash

我有一个看起来像这样的行数组:

[
  { 
    metric1: 50,
    metric2: 60
  },
  {
    metric1: 100,
    metric2: 120;
  }
]

我想将其缩减为一行,如下所示:

{
  metric1: 150,
  metric2: 180
}

到目前为止,我有一个非常简单的方法:

_.reduce(function(row, aggregate) {
  _.each(row, function(value, metric) {
    aggregate[metric] = aggregate[metric] || 0;
    aggregate[metric] += value;
  });
  return aggregate;
}, {});

但我真的觉得使用 Underscore 或 Lodash 函数式编程可以做得更干净。有什么想法吗?

你可以用原版的 javascript:

var result = data.reduce(function(totals, v) {
    totals.metric1 += v.metric1;
    totals.metric2 += v.metric2;
    return totals;
}, {metric1: 0, metric2: 0});

编辑:如果直到运行时才知道指标名称,您的解决方案可以正常工作。这是另一个使用 _.merge 的解决方案:

var result = _.merge.apply(null, [{}].concat(data).concat(function(total, v) {
  return (total || 0) + v;
}));

或者如果您使用的是 ES6:

var result = _.merge({}, ...data, (total=0, v) => {
  return total + v;
});