我正在尝试使用Jquery在JSON中汇总col1,col2和col3,但不确定如何使用.each循环进行操作.另一个问题是col1,col2和col3是动态的,因此名称将不断更改.
I am trying to sum up a col1, col2, and col3 in my JSON using Jquery and not sure how to go about doing it using the .each loop. Another problem is col1, and col2, and col3 are dynamic so the names will be changing.
这是我的JSON字符串:
This is my JSON string:
var data = [ { "Country": "Spain", "Year": "2012", "col1": "100.75", "col2": "500", "col3": "200" }, { "Country": "Spain", "Year": "2013", "col1": "200", "col2": "500", "col3": "300" }, { "Country": "France", "Year": "2011", "col1": "100", "col2": "100", "col3": "300" }, { "Country": "France", "Year": "2012", "col1": "100", "col2": "100", "col3": "300" }, { "Country": "France", "Year": "2013", "col1": "100", "col2": "200", "col3": "300" } ]jsfiddle/RHLKa/
我想要两个看起来像这样的结果:
I want two results that would look something like this:
1)每个国家/地区的总数
1) Totals per country
Spain 300.75, 1000, 500 France 300, 400, 9002)总计:
["col1", 600.75], ["col2", 1400], ["col3", 1400]谢谢 干杯
推荐答案要存储结果,最好使用对象(或关联数组).同样不要混用应该和不应该使用的属性-您可以将它们存储在单独的数组中,这可以是配置文件中的属性或类似的东西.这是代码( jsFiddle ):
To store results it's better to use object (or associative array). Also not to mix properties that should be applied and that should not - you may store them in a separate array, which could be a property in a config file or smth like that. Here is the code (jsFiddle):
var countries = {}, columns = {}, sumCols = ['col1', 'col2', 'col3']; $.each(data, function(index, obj) { if (!countries[obj['Country']]) { countries[obj['Country']] = {}; } $.each(sumCols, function (index, col) { if (!countries[obj['Country']][col]) { countries[obj['Country']][col] = 0; } if (!columns[col]) { columns[col] = 0; } var val = parseFloat(obj[col]); if (!isNaN(val)) { countries[obj['Country']][col] += val; columns[col] += val; } }); });结果:
{ "Spain":{ "col1":300.75, "col2":1000, "col3":500}, "France":{ "col1":300, "col2":400, "col3":900 } } { "col1":600.75, "col2":1400, "col3":1400 }更多推荐
使用jQuery的JSON响应中的总和值
发布评论