0

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

Community
  • 1
  • 1
Neal Jones
  • 450
  • 5
  • 19

4 Answers4

2

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];
  }
});
SimpleJ
  • 13,812
  • 13
  • 53
  • 93
1
info.forEach(function (item) {
    if (stateName[item.state]) {
        item.state = stateName[item.state];
    }
}

Would be one way.

The Witness
  • 910
  • 7
  • 12
1

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

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

info.forEach(function (inf) {
    if(inf.state in stateNames){
        inf.state = stateNames[inf.state];
    }
});

console.log(info);
Sufian Saory
  • 862
  • 9
  • 14
1

updated js bin is here http://jsbin.com/julexovete/1/edit?js,console

// Code
for(var i =0; i < info.length; i++){
  if(stateNames[info[i]["state"]]){
    info[i]["state"] = stateNames[info[i]["state"]];
  }

}
atul
  • 552
  • 4
  • 16