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.rowcountshouldj.rowcount.ideally should initialise
ivariable if haven't (i.e.varkeyword).(i've moved
var tdeclaration outside loop, make clear it's sametthroughout , you're changing value. shouldn't redeclarevareach 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); }
Comments
Post a Comment