jquery - Iterate over javascript object such that key variables are used as methods to call the object -


right i'm hard-coding new properties javascript application , horrible code smell don't know better when comes javascript implementation. code looks now:

$.getjson(url, function(data) {   $("#total_population_2013").html(data.table.total_population_2013);   $("#median_age_2013").html(data.table.median_age_2013);   //etcetera, long time might add }); 

its ruby openstruct object converted json i'm sending getjson method. trial , error solution, can access properties shown above.

i'm add many more variables i'll writing html id tags, , prefer more professional manner. here i've tried far not working:

$.getjson(url, function(data) {   for(var k in data) {     var value = data[k];     var id_str = "#"+k;     $(id_str).html(value);   }); } 

thanks

i notice 2 things. 1 for..in iterates on properties of object, can include stuff gets prototype chain. typically not want, want instead:

for(var k in data) if (data.hasownproperty(k)) {     ...  } 

this makes sure object's own properties.

second, json seems have data under data.table , instead you're pulling stuff out of data. means, you'll table value , don't have id #table. suspect want:

for(var name in data.table) if (data.table.hasownproperty(k)) {     $("#" + name).html(data.table[name]); } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -