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
Post a Comment