我正在尝试使用Jquery在我的JSON中总结col1,col2和col3,并且不确定如何使用.each循环来完成它。另一个问题是col1,col2和col3是动态的,因此名称将会改变。
这是我的JSON字符串:
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"
}
]
我想要两个看起来像这样的结果:
1)每个国家的总计
Spain 300.75, 1000, 500
France 300, 400, 900
2)总计:
["col1", 600.75],
["col2", 1400],
["col3", 1400]
由于 干杯
答案 0 :(得分:2)
要存储结果,最好使用对象(或关联数组)。也不要混合应该应用但不应该应用的属性 - 您可以将它们存储在单独的数组中,该数组可以是配置文件中的属性,也可以是类似的smth。这是代码(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
}
答案 1 :(得分:1)
使用动态属性名称将面临的主要问题是JavaScript明确不保证排序。因此,您无法真正匹配对象属性名称与数组索引的循环。因此,您需要使用对象来存储结果。这是一个应该工作的(不是非常优化的)代码。如果需要,您可以在之后操纵结果。
var results = {};
var totals = {};
// Loop over the array of data
for (var d = 0; d < data.length; d++) {
var o = data[d];
var country = o["Country"];
var values = results[country] || {};
// Since the column names may change, we need to loop over the object
for (var key in o) {
// Weed out the two known keys
if (o.hasOwnProperty(key) && key.toLowerCase() != "country" && key.toLowerCase() != "year") {
// Now find the entry in the values obj that matches
var column = values[key] || 0;
// And the corresponding entry in the totals object
var totalsColumn = totals[key] || 0;
column += parseFloat(o[key]);
totalsColumn += parseFloat(o[key]);
values[key] = column;
totals[key] = totalsColumn;
}
}
results[country] = values;
}
这会产生两个对象results
,如下所示:
France:
col1: 300
col2: 400
col3: 900
Spain:
col1: 300.75
col2: 1000
col3: 500
和totals
,看起来像这样:
col1: 600.75
col2: 1400
col3: 1400
我已将其发布到您fiddle的更新版本中。