sday
sday

Reputation: 1051

reference json numeric key with variable in javascript

How to loop through this data: (I have no control over format)

{"rowCount":3,"1":{"K":"2009","V":"Some Data"},"2":{"K":"2010","V":"More Data"}}

Above is a console.log(results) and results is a string

var r = JSON.parse(results);
var t;

for(var i=1;i<=r.rowCount;i++) {
    t=r[i].V;
    tableData.push(     
        {title:t, year:'2009', hasChild:true, color: '#000'}
    );                                      
}               

Error: TypeError: 'undefined' is not an object (evaluating 'r[i].V')

I cannot get it to evaluate the variable i. What am I doing wrong? Thanks

UPDATE

The incoming data had a bad rowcount causing the error. The accepted answer however is correct... just user error on my part not catching the bad incoming data. Had I put a console.log inside the loop I would have realized the error was actually happening after two successful loops. oops

Upvotes: 0

Views: 128

Answers (1)

Shai
Shai

Reputation: 7317

  • I assume r.rowCount should be j.rowCount.

  • Ideally you should also initialise the i variable if you haven't already (i.e. with the var keyword).

  • (I've also moved the var t declaration outside the loop, to make it clear that it's the same t throughout and you're just changing its value. You shouldn't redeclare it with var each time – although I doubt this affects the output.)


var j = {"rowCount":2,"1":{"K":"name","V":"john"},"2":{"K":"name","V":"sue"}};  
var t;

for (var i = 1; i <= j.rowCount; i++) {
    t = j[i].V;
    console.log(t);
} 

Working demo – JSFiddle

Upvotes: 3

Related Questions