Jiert
Jiert

Reputation: 575

JavaScript: associating an integer with a long list of strings

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

Answers (3)

Bergi
Bergi

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

Wayne
Wayne

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

georg
georg

Reputation: 214959

Try using an object, like this:

dict = {
     "This is my string": 3000,
     "Some other string": 30001,
     etc
}

bar = dict[foo]

Upvotes: 3

Related Questions