如何使用 Underscore JS 计算嵌套 JSON 中的总和

How to Calculate the sum in nested JSON using Underscore JS

我收到 API 的 JSON 回复。我需要实现的主要目标是计算对象中所有# 的总和。为了简单起见,我想使用下划线来做到这一点,但我不明白我将如何实现这一点。

这是我的回复。

 [{
    "data": {          
            "row": [{
                "col": ["2015-02-10", "item1", "1"]
            }, {
                "col": ["2015-02-11", "item2", "1504"]
            }, {
                "col": ["2015-02-12", "item3", "66"]
            }, {
                "col": ["2015-02-13", "item4", "336"]
            }, {
                "col": ["2015-02-14", "item5", "19"]
            }, {
                "col": ["2015-02-15", "item6", "210"]
            }, {
                "col": ["2015-02-16", "item7", "36"]
            }, {
                "col": ["2015-02-17", "item8", "1742"]
            }, {
                "col": ["2015-02-18", "imem9", "61"]
            }, {
                "col": ["2015-02-19", "item10", "22"]
            }]
        }
    }
}]

你不需要下划线 - 你可以用 Array.prototype.reduce 来完成,它是 JavaScript 提供的 _ 风格的函数之一:

var total = input[0].data.row.reduce(function (sum, element) {
    return sum + (+element.col[2]) 
}, 0);

我假设您要求和的数字是每个 col 数组中的第三个元素,例如22 对于 ["2015-02-19", "item10", "22"]

如果你真的想为此使用 Underscore,只需 group/reduce 把它记下来并总结一下。

var groups = _(items).groupBy(function(o) {
    return o.col[1];
});

var sum2 = {};
_.each(groups, function(group, key) {
  sum2[key] = _.reduce(group, function(memo, item) {
    return memo + (parseInt(item.col[2]) || 0);
  }, 0);
});