问题的简化版本 我有一个看起来像这样的对象:
var info = [{
"population": 1234,
"state": "AL"
},{
"population": 1234,
"state": "AK"
}]
我需要将州两字母缩写替换为实际的州名。我有以下内容:
var stateNames = {
"AL": "Alabama",
"AK": "Alaska"
};
目标是让它产生:
[{
"population": 1234,
"state": "Alabama"
},{
"population": 1234,
"state": "Alaska"
}]
我已经盘旋了这么久,我很困惑。我对自己的指示是这样的:
某些可能的相关代码:
我一直在寻找可能的解决方案,尽管花了很多时间,但没有太多的东西可以提供。我认为使用foreach可能是正确的,我认为this SO question/answer是正确的方向:
Object.keys(hashmap).forEach(function(key) {
var newkey = key + "xxx";
hashmap[newkey] = hashmap[key];
delete hashmap[key];
});
但我无法成功地适应它。非常感谢任何帮助或建议 - 感谢阅读!
答案 0 :(得分:2)
您可以使用其短名称作为stateNames
中的密钥来解析州的全名。基本上:stateNames[shortName] = longName
。您可以使用Object.prototype.hasOwnProperty
检查stateNames
是否包含特定密钥。这是一种方法:
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];
}
});
答案 1 :(得分:1)
info.forEach(function (item) {
if (stateName[item.state]) {
item.state = stateName[item.state];
}
}
将是一种方式。
答案 2 :(得分: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);

答案 3 :(得分:1)
更新的js bin在这里 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"]];
}
}