聚合扁平物体

时间:2015-08-21 07:13:42

标签: javascript node.js

我有很多具有相同扁平结构但不同整数值的对象。 问题是我不知道结构,我只知道它是一致的。

现在我想把它们聚合成一个对象。

所以我有一个函数可以将两个对象的所有元素相加。

function objectAddition(s1, s2) {
    for(i in s2) {
        s1[i] = (s1[i] || 0) + s2[i];   
    }
}

并为每个对象调用此方法。

var total = {};
for(i in objs) {
    objectAddition(total, objs[i]);
}

有更快的方法吗?

1 个答案:

答案 0 :(得分:0)

你肯定想看看LoDash

// the third parameter to _.reduce is its accumulator, it's set to {} as was your `total`
var total = _.reduce(objs, function(acc, item){
       // acc is the accumulator, it becomes the thisArg of the _.forEach
       _.forEach(_.keys(item), function(key){
          this[key] = (this[key] || 0 ) + item[key];
       }, acc);
       return acc;
     }, {});