So, I have 3 variables being passed in:
- stats (JSON object, shown below)
- place_type (string, either “US” or “State”)
- factor (string)
I have another variable, answer, whose value depends on the other variables. For example, if place_type = “State” and factor = “factor2”, then
var answer = stats.State.factor2; // equals "E"
I’m trying to see if there’s a way to dynamically assign a variable without needing to use eval().
// Simplified, there are many more than 3 factors
var stats = {
"US": {
"factor1" : "A",
"factor2" : "B",
"factor3" : "C"
},
"State": {
"factor1" : "D",
"factor2" : "E",
"factor3" : "F"
}
}
Using eval(), this is how it’s done:
eval("var answer = stats." + place_type + "." + factor + ";");
Is this possible in JS without needing eval() or a ton of different IF loops? Thanks in advance.
Here you go:
Live demo: http://jsfiddle.net/simevidas/NsT8Y/
Consider putting this in a try-catch block since you chain property accessors. If the
place_typeproperty does not exist instats, thenstats[place_type]will returnundefined, andundefined[factor]will throw an error.