对于看起来像这样的JSON对象:
[{
"gemeente": "amsterdam",
"stadsdeel": "centrum",
"adres": "damrak 28-30",
"bvo": "2000",
},
{
"gemeente": "amsterdam",
"stadsdeel": "centrum",
"adres": "damrak 66",
"bvo": "1500",
"": ""
}]
我正在尝试获得bvo
值的总和。在这种情况下输出将是3500.然后我需要使用此数字进行数据可视化。我正在d3.js
工作,但任何Javascript解决方案都可以。
答案 0 :(得分:3)
D3使用d3.sum很好地处理了这个问题,没有经过适当的测试我认为语法应该类似于
d3.sum(list, function(d) { return d.bvo; });
答案 1 :(得分:1)
您需要的是
var list = [{
"gemeente": "amsterdam",
"stadsdeel": "centrum",
"adres": "damrak 28-30",
"bvo": "2000",
},
{
"gemeente": "amsterdam",
"stadsdeel": "centrum",
"adres": "damrak 66",
"bvo": "1500",
"": ""
}];
// code to sum the values
var sum = 0;
for(var len = list.length, i=0; i < len; i++){ // for each object in the list
var item = list[i];
sum += parseInt(item.bvo, 10); // parse its "bvo" element as integer and add it to the sum
}
// output to console the sum.. or do whatever you want with the sum here..
console.log(sum);
答案 2 :(得分:0)
我通过常规Javascript得到答案:
var SumByTipe = {};
for (i in data) {
var currtipe = data[i].tipe;
if (currtipe in SumByTipe) {
for (j in data[i]) {
if (j != "tipe" && j != "mc") {
SumByTipe[currtipe][j + '_total'] += parseFloat(data[i][j]);
}
}
}
else {
var firstSum = {};
for (j in data[i]) {
if (j != "tipe" && j != "mc"){
firstSum[j + '_total'] = parseFloat(data[i][j]);
}
}
SumByTipe[currtipe] = firstSum;
}
}
console.log(SumByTipe);
虽然我并没有真正得到 它如何工作,但它运作良好。 : - )