Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the quickest way to assign a variables based on an array?

What's the quickest way, from a readability/typing standpoint, to assign a value to a specific variable based on a related variable?

var abbrev;

if(state=='Pennsylvania'){
    abbrev='PA';
}else if(state=='New Jersey'){
    abbrev='NJ';
}else if(state=='Delaware'){
    abbrev='DE';
}
//and so on...

I'm trying to avoid making one array for the state name and a another array for the abbreviation because the relationship is lost with separate declarations.

like image 524
koleslaw Avatar asked Mar 08 '23 21:03

koleslaw


2 Answers

You could use an object for the abbreviation, like

var abbreviations = {
        'Pennsylvania': 'PA',
        'New Jersey': 'NJ',
        'Delaware': 'DE'
    };

Usage:

abbrev = abbreviations[state];
like image 159
Nina Scholz Avatar answered Apr 28 '23 05:04

Nina Scholz


just a suggestion, have you tried using CASE? it looks more clean and readable

like image 37
Makamu Evans Avatar answered Apr 28 '23 04:04

Makamu Evans