Javascript Array and Object keys -


i have json response i'm getting custom web service looks following:

var data = {      az:{charge:123,count:324},     tn:{charge:123,count:7545},     tx:{charge:165,count:345} } 

and wish loop through using array of state abbreviations via json call. don't need loop through states specific ones dictated json call. end array of state abbreviations looks so:

var states = ["az","tx"]; 

then attempt loop through data , pull out charge property so:

console.log(data[states[i]].charge); 

however when undefined data. when out state abbreviation it's there , when log out data right before call data there. can reference each record in data doing following though

console.log(data["tn"].charge); 

anyone care explain why console.log(data[states[i]].charge); other does? can rectify problem?

you using ax , tx keys data not strings, variables. add quotes make them strings.

var states = ['ax','tx']; 

and avoid possible error in code, check if data[states[i]] not undefined before trying access charge property.

var statedata = data[states[i]];  if(!statedata) return; //or `continue` if inside loop skip  console.log(statedata.charge); 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -