0

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

Jiert
  • 565
  • 1
  • 5
  • 11

3 Answers3

3

Try using an object, like this:

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

bar = dict[foo]
georg
  • 211,518
  • 52
  • 313
  • 390
1

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];
Wayne
  • 59,728
  • 15
  • 131
  • 126
1

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];
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375