Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用下划线JS计算嵌套JSON中的和_Javascript_Json_Math_Underscore.js - Fatal编程技术网

Javascript 如何使用下划线JS计算嵌套JSON中的和

Javascript 如何使用下划线JS计算嵌套JSON中的和,javascript,json,math,underscore.js,Javascript,Json,Math,Underscore.js,我得到的是来自API的JSON响应。我需要实现的主要目标是计算对象中所有#的总和。为了简单起见,我想使用下划线来实现这一点,但我无法理解如何实现这一点 这是我的回答 [{ "data": { "row": [{ "col": ["2015-02-10", "item1", "1"] }, { "col": ["2015-02-11", "item2", "

我得到的是来自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"]
            }]
        }
    }
}]

这不需要下划线-可以使用它,这是JavaScript提供的
\uuu
风格的函数之一:

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

我假设要求和的数字是每个
数组中的第三个元素,例如
[“2015-02-19”、“item10”、“22”]
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);
});