Reputation: 575
I'm receiving strings from JSON and need to associate them with an integer. So for example I currently use this method:
var foo = "This is my string";
var bar;
if (foo === "This is my string"){
bar = 3000;
} else if (foo === "Some other string"){
bar = 30001;
}
The problem is that I have ~50 strings I need to associate, and it seems like this huge block of if/else statements can be done in a more efficient way.
Is there any way to make these associations in a more concise and efficient manner?
Cheers
Upvotes: 0
Views: 73
Reputation: 664579
See my detailed answer on the possible duplicate Alternative to a million IF statements
In your case, it would be something like
var bar = {
"This is my string": 3000,
"Some other string": 30001,
...
}[foo];
Upvotes: 1
Reputation: 60414
Create a map:
var lookup = {
"This is my string": 3000,
"Some other string": 30001
};
And set bar
to the correct value in the table:
var bar = lookup[foo];
Upvotes: 1
Reputation: 214959
Try using an object, like this:
dict = {
"This is my string": 3000,
"Some other string": 30001,
etc
}
bar = dict[foo]
Upvotes: 3