使用jQuery的JSON响应中的总和值

编程入门 行业动态 更新时间:2024-10-07 06:38:00
本文介绍了使用jQuery的JSON响应中的总和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用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, 900

2)总计:

["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响应中的总和值

本文发布于:2023-11-26 21:42:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635302.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   jQuery   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!