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

How to Calculate the sum in nested JSON using Underscore JS

本文关键字:JSON 嵌套 何使用 Underscore JS 计算      更新时间:2023-09-26

我从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"]
            }]
        }
    }
}]

如果你真的想使用下划线,只需将其分组/减少并求和即可。

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

您不需要下划线-您可以使用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"]