javascript 对 JSON 数组响应中的值求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17015931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum values in JSON array response
提问by nielsfogt
I have a JSON string from an API response which looks like this:
我有一个来自 API 响应的 JSON 字符串,如下所示:
{ "legend_size": 1,
"data": {
"series": [ "2013-05-01", "2013-05-02" ],
"values": {
"Sign Up": {
"2013-05-05": 10,
"2013-05-04": 10
}
}
}
}
I'd like to sum the values in the "Sign Up" Object (10 + 10). The challenge I am having is that the key's are unique and most of the posts demonstrating how to do something like this show examples where it is just an array of values or the keys are consistent (ie - every key is "value").
我想对“注册”对象 (10 + 10) 中的值求和。我面临的挑战是键是唯一的,并且大多数演示如何执行此类操作的帖子都显示了示例,其中它只是一组值或键是一致的(即 - 每个键都是“值”)。
Should I be attempting to use the Series array to loop through the Sign Up Object?
我应该尝试使用 Series 数组循环遍历 Sign Up 对象吗?
回答by jcsanyi
Assuming you've already got your data parsed into an object, you can use a for loop like this:
假设您已经将数据解析为一个对象,您可以使用这样的 for 循环:
var json = {
"legend_size": 1,
"data": {
"series": [ "2013-05-01", "2013-05-02" ],
"values": {
"Sign Up": {
"2013-05-05": 10,
"2013-05-04": 10
}
}
}
};
var sum = 0;
for (x in json.data.values['Sign Up']) {
sum += json.data.values['Sign Up'][x];
}
Basically, we navigate through the json data to get the the actual data that we want... which is the 'Sign Up' object. Then we use a for/in
loop to loop through all the keys that that object has, and add up the values.
基本上,我们浏览 json 数据以获取我们想要的实际数据......这是“注册”对象。然后我们使用for/in
循环遍历该对象具有的所有键,并将这些值相加。
回答by jcsanyi
After you've parsed it, here's a way to arrive at the sum by using Array.prototype.reduce
.
在您解析它之后,这里有一种使用Array.prototype.reduce
.
var vals = object.data.values["Sign Up"];
var result = Object.keys(vals)
.reduce(function(sum, key) {
return sum + vals[key]
}, 0);
The .reduce()
and .keys()
methods will need shims for IE8 and lower.
该.reduce()
和.keys()
方法将需要IE8垫片和降低。