Neal Jones Neal Jones - 2 months ago 5
Javascript Question

How to replace object value based on hash table (ex. "State": "CO" changes to "State": "Colorado")

Simplified Version of Problem:
I have an object that looks like this:

var info = [{
"population": 1234,
"state": "AL"
},{
"population": 1234,
"state": "AK"
}]


I need to replace the state two letter abbreviation with the actual state name. I have this available as follows:

var stateNames = {
"AL": "Alabama",
"AK": "Alaska"
};


The goal is to have it result in this:

[{
"population": 1234,
"state": "Alabama"
},{
"population": 1234,
"state": "Alaska"
}]


I have circled this long enough that I am pretty confused. My instructions to myself go like this:


  1. Check every info.state value to see if it matches a key within stateNames.

  2. If it matches, replace the info.state value with that stateNames value.

  3. If there is no match, leave it.

  4. Return object.



Some Possibly Related Code:

I have been searching SO for possible solutions and despite putting a good bit of time, don't have too much to offer. I do think using a foreach is probably right, and I think this SO question/answer is in the right direction:

Object.keys(hashmap).forEach(function(key) {
var newkey = key + "xxx";
hashmap[newkey] = hashmap[key];
delete hashmap[key];
});


But I haven't been able to successfully adapt it. Any help or advice is very appreciated - thanks for reading!

A JS Bin:
http://jsbin.com/nojamoyeya/2/edit?js,console

Answer

You can resolve a state's full name by using its short name as the key in stateNames. Basically: stateNames[shortName] = longName. You can use Object.prototype.hasOwnProperty to check if stateNames contains a specific key. Here is one way to do it:

var info = [{
   "population": 1234,
   "state": "AL"
},{
   "population": 1234,
   "state": "AK"
}];

var stateNames = {
  "AL": "Alabama",
  "AK": "Alaska"
};

info.forEach(function(state) {
  if(stateNames.hasOwnProperty(state.state)) {
    state.state = stateNames[state.state];
  }
});
Comments