通过 Ajax 请求 (GET) 解析值后,我需要将它们替换为其他值 -> 即对应于同一国家代码的多个邮政编码(“1991,1282,6456”:“Idaho”等)
这是我到目前为止所做的:
$mapCodes = {
'1991': 'Idaho',
'1282': 'Idaho',
'5555': 'Kentucky',
'7777': 'Kentucky '
}
var region = value.groupid.replace(/7777|5555|1282|1991/, function(matched) {
return $mapCodes[matched];
});
console.log(region);
这可行,但我宁愿避免将我的 $mapCodes 变量设置为一长串重复的值。
我需要类似的东西和数组的数组来匹配(然后替换)
$mapCodes = {
'1991,1282' : 'Idaho',
'7777,5555' : 'Kentycky'
}
最佳答案
您需要使用数组,其中元素是 $mapCodes 的键:
{
"Idaho":[1991,1282]
}
这是演示:
$mapCodes = {
"Idaho":['1991','1282'],
"Kentucky":['5555','7777']
}
var test="1991 7777 1282"; /// input string
var region = test; // result string
for(let key in $mapCodes){
let a =$mapCodes[key];
for(let i=0; i<a.length; i++) {
region = region.replace(a[i],key);
}
}
console.log(region);
关于Javascript - 将值匹配(并替换)到数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53865426/