[英]how to sum up all values with same keys in an object inside an array and get their average
so i have this json and i need to add the values of each the same keys that the object has and will also compute their average, here is my json 所以我有这个json,我需要添加对象具有的每个相同键的值,并且还要计算它们的平均值,这是我的json
var arraySeries = [{"country":"United States","data":2},
{"country":"Venezuela","data":0},
{"country":"Singapore","data":3},
{"country":"United States","data":0},
{"country":"Germany","data":2},
{"country":"United States","data":2},
{"country":"Canada","data":2},
{"country":"Germany","data":-4}];
and here is my expected result 这是我的预期结果
var newArraySeries = [{"country":"United States","data":[1.33333]},
{"country":"Venezuela","data":[0]},
{"country":"Singapore","data":[3]},
{"country":"Canada","data":[2]},
{"country":"Germany","data":[-1]}];
the data in newArraySeries should be in array, I'm going to use it in my highchart map.. i did some google research but i can't find any article like this.I hope you can help me newArraySeries中的数据应该在数组中,我将在highchart映射中使用它。.我做了一些google研究,但找不到任何这样的文章。希望您能对我有所帮助
Solved with standard javascript and using temp variables 用标准javascript解决并使用临时变量
var countries = {}
var countries_count = {}
var newArraySeries = []
arraySeries.forEach(
function(e){
if(!countries[e.country]){
countries[e.country] = 0
countries_count[e.country] = 0
}
countries[e.country] += e.data
countries_count[e.country]++
}
)
for(var country in countries){
newArraySeries.push({country : country, data : countries[country] / countries_count[country]})
}
You can do it with Alasql library. 您可以使用Alasql库来实现。
var arraySeries = [{"country":"United States","data":2},
{"country":"Venezuela","data":0}];
var res = alasql('SELECT country, AVG(data) AS data FROM ? GROUP BY country',
[arraySeries]);
Try this example at jsFiddle. 在jsFiddle尝试此示例 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.