groc426
groc426

Reputation: 319

Object returning NaN when sum values

I'll admit I'm weak in JavaScript and JSON. I've spent a lot of time attempting to figure out why numbers from my objects returns NaN when they are added together. With that in mind, below is my JSON, stored to a variable:

var data = [
    {
        "acc_ext_id": null,
        "cat_code": 10002,
        "cat_ds": "REVENUE",
        "category_id": null,
        "chart_id": null,
        "created_at": null,
        "dept_id": null,
        "feb": null,
        "id": null,
        "jan": 30,
        "note": null,
        "total_cost": null,
        "updated_at": null,
        "year_id": null
    },
    {
        "acc_ext_id": "41260-02600",
        "cat_code": 10002,
        "cat_ds": "REVENUE",
        "category_id": 2,
        "chart_id": 2373,
        "created_at": "2013-01-15 16:43:52.169213",
        "dept_id": 86,
        "feb": 45,
        "id": 3,
        "jan": 60,
        "note": "Two",
        "total_cost": 105,
        "updated_at": "2013-01-15 16:43:52.169213",
        "year_id": 1
    }
]

I then attempt to iterate over the objects and sum the values:

var jan;

for (var i=0;i<data.length;i++){ 
    if(data[i].jan != null){    
        jan += parseFloat(data[i].jan);
        console.log(jan);
    }
}

Printed out in the console is NaN. I've attempted to parse the number as well as leave it raw, but to no avail. Is there something wrong with my objects? Here is a jsFiddle to illustrate: http://jsfiddle.net/5E2pm/3/

Upvotes: 6

Views: 34580

Answers (3)

martinedwards
martinedwards

Reputation: 5825

2021

This is a good use for a reducer

const jan = data.reduce(function(total, current) {
 return total + current.jan;
}, 0); // starting value

OLD ANSWER

I like this approach. It basically sets the value to 0 on the first iteration when jan doesn't exist.

jan = (jan || 0) + parseFloat(data[i].jan);

Upvotes: 7

Sir
Sir

Reputation: 8277

var jan = 0; //this should solve it

for (var i=0;i<data.length;i++){ 
    if(data[i].jan != null){    
        jan += parseFloat(data[i].jan);
        console.log(jan);
    }
}

Try this should solve it :)

Explanation as quoted by DON in comments below:

var jan; this will declare variable as undefined, so when you try to add values with undefined you will get as NaN, so the answer here with var jan = 0 will work – DON

Upvotes: 15

sourcecode
sourcecode

Reputation: 1802

you need to initialize jan first

var jan = 0; 

here's the example - link

Upvotes: 1

Related Questions