reference json numeric key with variable in javascript -


how loop through data: (i have no control on format)

{"rowcount":3,"1":{"k":"2009","v":"some data"},"2":{"k":"2010","v":"more data"}} 

above console.log(results) , results 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' not object (evaluating 'r[i].v')

i cannot evaluate variable i. doing wrong? thanks

update

the incoming data had bad rowcount causing error. accepted answer correct... user error on part not catching bad incoming data. had put console.log inside loop have realized error happening after 2 successful loops. oops

  • i assume r.rowcount should j.rowcount.

  • ideally should initialise i variable if haven't (i.e. var keyword).

  • (i've moved var t declaration outside loop, make clear it's same t throughout , you're changing value. shouldn't redeclare var each time – although doubt affects output.)


var j = {"rowcount":2,"1":{"k":"name","v":"john"},"2":{"k":"name","v":"sue"}};   var t;  (var = 1; <= j.rowcount; i++) {     t = j[i].v;     console.log(t); }  

working demo – jsfiddle


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -