javascriptfunctionargumentsabbreviation

Get a state name from abbreviation


I have an app in place that returns states abbreviation if the state is clicked. I would like to put a user message in place in the app that would require the actual state name and not the abbreviation.

If I click New York state, I have "NY" stored in a variable named data.name. How can I use this data to get the full name of a state based off of its abbreviation?

I was thinking of using

var getStateInfo = function (abbrev, stateName) {

}

but I am not sure what I would put inside the function. I am also aware that there's probably a better approach to this. Any help would be great. Thanks!


Solution

  • You can use a javascript object as a dictionary:

    var states = {"NY":"New York", "NJ":"New Jersey"};
    

    and access them like this:

    alert(states["NY"]);
    

    so your function that returns the full state name would work like this:

    var getStateFullName = function (stateAbbr) {
      return states[stateAbbr];
    }