snOw
snOw

Reputation: 3

Select specific JSON key's value to sum it

For a JSON object that looks like this:

[{
    "gemeente": "amsterdam",
    "stadsdeel": "centrum",
    "adres": "damrak 28-30",
    "bvo": "2000",
},
{
    "gemeente": "amsterdam",
    "stadsdeel": "centrum",
    "adres": "damrak 66",
    "bvo": "1500",
    "": ""
}]

I'm trying to get a total sum of the bvo value. the output would in this case be 3500. Then I need to use this number for a data visualisation. I'm working whith d3.js but any Javascript solution would do.

Upvotes: 0

Views: 1631

Answers (3)

Ben
Ben

Reputation: 13635

D3 handles this quite well with d3.sum, without proper testing I think the syntax should be something like

d3.sum(list, function(d) { return d.bvo; });

Upvotes: 3

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

What you need is

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);

Upvotes: 1

snOw
snOw

Reputation: 3

I got the answer with regular 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);

Though I don't really get how it works, it worked fine. :-)

Upvotes: 0

Related Questions