简体   繁体   中英

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

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];
  }
});
info.forEach(function (item) {
    if (stateName[item.state]) {
        item.state = stateName[item.state];
    }
}

Would be one way.

 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); 

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"]];
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM