使用jQuery的JSON响应中的总和值 [英] Sum values in JSON response with jquery

查看:138
本文介绍了使用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"
}
]

http://jsfiddle.net/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响应中的总和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆