0

对于如下所示的 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 解决方案都可以。

4

3 回答 3

3

D3 用d3.sum很好地处理了这个问题,没有适当的测试我认为语法应该是这样的

d3.sum(list, function(d) { return d.bvo; });
于 2013-06-01T18:04:34.500 回答
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);
于 2013-01-22T15:40:34.920 回答
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);

虽然我真的不明白它是如何工作的,但它工作得很好。:-)

于 2013-01-22T12:26:48.563 回答