JIMMY THE CODE
JIMMY THE CODE

Reputation: 159

How to iterate over a json object list?

i am struggling how to sum all the values of "B" in my json object. I want the console log to show me the grand total of all the "B" values.

var voltot = 0;

$.each(json,function(k,v){

    voltot = v.B += voltot ;

    //console.log(v.B);

});

console.log(voltot);

HERE IS MY FULL JSON OBJECT.

var json=
[
    {
        "a": "OOCBER",
        "b": "OOCL BERLIN",
        "c": "CHINA",
        "d": "GREAT BRITAIN",
        "e": "*PI",
        "f": "NGB",
        "g": "CN",
        "i": "GB",
        "n": 9,
        "o": 6,
        "p": "2015-09-14",
        "q": "2015-09-14",
        "s": 4,
        "u": "40HC",
        "v": "TRLU7564566",
        "w": "CN0794909",
        "x": "LEIGH",
        "y": "NINGBO",
        "z": 395,
        "B": 68.8,
        "C": 7987.5,

    },
    {
        "a": "OOCBER",
        "b": "OOCL BERLIN",
        "c": "CHINA",
        "d": "GREAT BRITAIN",
        "e": "*PI",
        "f": "NGB",
        "g": "CN",
        "i": "GB",
        "n": 9,
        "o": 6,
        "p": "2015-09-14",
        "q": "2015-09-14",
        "s": 4,
        "u": "40HC",
        "v": "TCLU8306124",
        "w": "CN0786008",
        "x": "OXFORDSHIRE",
        "y": "NINGBO",
        "z": 412,
        "B": 68,
        "C": 8790.5,

    }
]

i am struggling how to sum all the values of "B" in my json object. I want the console log to show me the grand total of all the "B" values.

var voltot = 0;

$.each(json,function(k,v){

    voltot = v.B += voltot ;

    //console.log(v.B);

});

console.log(voltot);

Upvotes: 0

Views: 105

Answers (4)

Aaron
Aaron

Reputation: 24802

The preferred method to obtain an unique value from an array is the Array.prototype.reduce method, which takes a callback function and a starting value (it reduces an array to a single value). You could use it this way :

json.reduce(function(total, current) { return typeof current.B === "number" ? total + current.B : total; }, 0);

Here is a JSFiddle.

Upvotes: 0

Oliver
Oliver

Reputation: 1380

The operator += is incorrect. @RiccardoC answer was correct.

Also, you don't need to use jquery to sum the values. You could simply do the following

var voltot=0;
json.forEach(function(element) {voltot+=element.B})

The forEach function will run a callback for each element of your array

Upvotes: 0

Amel
Amel

Reputation: 708

Here's JSFiddle. I just shrunk json and post. Try with full json array

var json=
[
    {

        "z": 395,
        "B": 68,
        "C": 7987.5,

    },
  {

        "z": 395,
        "B": 68,
        "C": 7987.5, 
    }
];

var voltot = 0;

$.each(json,function(k,v){
    voltot += v.B;
});

console.log(voltot);

Upvotes: 0

RiccardoC
RiccardoC

Reputation: 866

This is wrong

voltot = v.B += voltot ;

Make like this

voltot += v.B;

Or

voltot = v.B + voltot ;

Upvotes: 4

Related Questions