如何在数组内的对象中使用相同的键来汇总所有值并获得它们的平均值

时间:2014-11-29 15:18:36

标签: javascript json highcharts

所以我有这个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}];

这是我的预期结果

var newArraySeries = [{"country":"United States","data":[1.33333]},
                   {"country":"Venezuela","data":[0]},
                   {"country":"Singapore","data":[3]},
                   {"country":"Canada","data":[2]},
                   {"country":"Germany","data":[-1]}];

newArraySeries中的数据应该在数组中,我将在我的高清地图中使用它...我做了一些谷歌研究,但我找不到这样的文章。我希望你能帮忙我

2 个答案:

答案 0 :(得分:2)

使用标准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]})
}

答案 1 :(得分:-1)

您可以使用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]);

在jsFiddle尝试this example