使用lodash对属性子对象求和

时间:2015-01-13 09:41:13

标签: javascript lodash

我在我的项目中使用lodash。我有一个JSON

 { arcade: {
    sam: {
        played: 10,
        wins: 5,
        lose: 5
      },
     adam: {
       played: 10,
       wins: 5,
       lose: 5
     },
  }

  pvp: {
    sam: {
        played: 10,
        wins: 5,
        lose: 5
      },
     adam: {
       played: 10,
       wins: 5,
       lose: 5
     },
  }
}

我希望收到JSON

的结果
{
  arcade: {
    played: 20,
    wins: 10,
    lose: 10
  },
  pvp: {
    played: 20,
    wins: 10,
    lose: 10
  },
}

如何使用js / lodash计算子对象的值总和? 感谢。

1 个答案:

答案 0 :(得分:2)

http://jsfiddle.net/efmmh8ok/
我会使用reduce函数(lodash doc

 _.reduce(ori, function (ori1, data1, c) {
    ori1[c] = _.reduce(data1, function (ori2, data2) {
        _.each(data2, function (value, key) {
            ori2[key] = ori2[key] || 0; // if it undefined yet put number 0 
            ori2[key] += value; // sum with the previous value
        });
        return ori2; // the populated data {played: 20, wins: 10, lose: 10}
    }, ori1[c] || {});
    return ori1; // the populated data {pvp: {played: 20, wins: 10, lose: 10}}
}, {});