如何使用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"]
}]
}
}
}]
如果你真的想使用下划线,只需将其分组/减少并求和即可。
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"]
。
相关文章:
- Javascript-JSON-嵌套和分组
- JSON 嵌套 Ul 来自 Javascript 中的单维或多维 json 对象
- 如何从 json 嵌套结构中获取键的 json 值
- 如何使用角度获取这些 json 嵌套值
- 使用jquery加载json嵌套对象
- 如何在JavaScript中从url解析json(嵌套)
- 如何在 Python 和 JavaScript 中以相同的方式散列“json”嵌套字典
- 对象和数组的复杂 JSON 嵌套
- JSON嵌套对象分析
- Evaluate Json-嵌套的Json路径以字符串形式提供
- JSON嵌套“;第n级”;对象数组转换为多维数组
- jQuery JSON嵌套循环
- 查找使用多个字符串值的JSON嵌套节点
- 浏览json嵌套文件
- Angularjs的ng-repeat下拉菜单从json嵌套
- JSON嵌套对象vs Javascript数组
- 重复使用不同的json嵌套
- 我如何使用d3.js导航JSON嵌套文件
- Grails 2.4.4绑定JSON嵌套对象
- JSON 嵌套解析帮助使用 $.each