javascript - jQuery JSON to multi dimensional array -
so have jquery .getjson so:
var tournamentdata = []; $.getjson( "http://tourn.dev/data/tournaments", function( data ) { $.each(data, function(i) { var tempdata = []; $.each(this, function(k, v) { tempdata.push(v); }); tournamentdata.push(tempdata); }); }); console.log(tournamentdata); the json request returns:
[ { "id":1, "name":"one", "max_users":100, "registered_users":0, "prize_pool":1000, "entry_fee":10, "published":0, "registration_open_date":"0000-00-00 00:00:00", "registration_close_date":"0000-00-00 00:00:00" ,"start_date":"0000-00-00 00:00:00", "created_at":"2015-04-28 20:35:23", "updated_at":"2015-04-28 20:35:23" }, { "id":2, "name":"two", "max_users":1000, "registered_users":0, "prize_pool":10000, "entry_fee":100,"published":0, "registration_open_date":"0000-00-00 00:00:00", "registration_close_date":"0000-00-00 00:00:00", "start_date":"0000-00-00 00:00:00", "created_at":"2015-04-28 20:37:16", "updated_at":"2015-04-28 20:37:16" } ] now, when check console log in firefox tournamentdata array of 2 arrays 'array [ array[12], array[12] ]'.
however, when try access multi-array through like:
alert(tournamentdata[0][0]); it returns undefined.
what seeing in console live reference of array , looks right....but not snapshot , changed array gets changed
however try stringifying in code in question , see empty array. why? because ajax hasn't completed @ time trying access data.
the live reference looks right because console isn't showing exaclty array looked @ time logged, show subsequent changes ...due prototypical inheritance
you can see in demo code:
var tournamentdata = []; $.getjson("data.json", function(data) { $.each(data, function(i) { var tempdata = []; $.each(this, function(k, v) { tempdata.push(v); }); console.log('push data now'); //fires after 1 below tournamentdata.push(tempdata); }); }); //this log empty array , fires before above logs console.log('log outside getjson', json.stringify(tournamentdata)); conclusion: if want access arrays , parse dom has done in $.getjson callback...the first a in ajax stands asynchronous
for explanation , must read working ajax see: how return response asynchronous call? .
Comments
Post a Comment