Javascript - assigning dynamic values without eval()
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:
var answer = stats[place_type][factor];
Live demo: http://jsfiddle.net/simevidas/NsT8Y/
Consider putting this in a try-catch block since you chain property accessors. If the place_type
property does not exist in stats
, then stats[place_type]
will return undefined
, and undefined[factor]
will throw an error.
var answer;
try {
answer = stats[place_type][factor];
} catch(e) {}
For this example, it's easy. The equivalent syntax to
var answer = stats.State.factor2;
is
var answer = stats["State"]["factor2"];
and the latter syntax will work with a variable in place:
var answer = stats[place_type][factor];
var answer = stats[place_type][factor];
精彩评论