首页 > 解决方案 > Javascript - 将值匹配(并替换)到数组数组

问题描述

通过 Ajax 请求(GET)解析值后,我需要将它们替换为其他值 -> 即对应于同一国家/地区代码的多个邮政编码(“1991,1282,6456”:“爱达荷州”等)

这是我到目前为止所做的:

$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'
}

标签: javascriptreplacematch

解决方案


您需要使用数组,其中元素是 $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);


推荐阅读