jquery - How do I extract JSON string using a JavaScript variable? -
i trying retrieve corresponding dial_code using name obtaining variable.
the application uses map of world. when user hovers on particular country, country obtained using 'getregionname'. used alter variable name. how can use variable name retrieve dial_code relates to?
json
var dialcodes = [ {"name":"china","dial_code":"+86","code":"cn"}, {"name":"afghanistan","dial_code":"+93","code":"af"} ]; the following code runs on mouse hover of country
var countryname = map.getregionname(code); label.html(name + ' (' + code.tostring() + ')<br>' + dialcodes[0][countryname].dial_code); this code doesn't work correctly. dialcodes[0][countryname].dial_code part causing error, i'm not sure how correctly refer corresponding key/value pair
if have support old browsers: loop on entries in array , compare given name:
var dialcode; for(var = 0; < dialcodes.length; i++) { if(dialcodes[i].name === countryname) { dialcode = dialcodes[i].dial_code; break; } } label.html(countryname + ' (' + dialcode + ')'); if browser support array.prototype.filter:
dialcodes.filter(function(e) { return e.name === 'china' })[0].dial_code
Comments
Post a Comment