javascript - 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'
}
解决方案
您需要使用数组,其中元素是 $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);
推荐阅读
- visual-studio - Visual Studio 和 Visual Studio Code 中的相同快捷方式
- makefile - 是否可以切断 Makefiles 中的依赖链?
- flutter - 在 Android 上开始录制视频时 Flutter 相机冻结
- c# - 使用 C# 从 Table 中找不到的文件夹中删除图像
- google-analytics - 在 Google Analytics 中删除另一个网站数据
- javascript - Fabric.js 小圆圈限制在画布中心的半径范围内
- javascript - 如何使用 Mongoose 过滤器显示嵌套数组中的数据?
- c++ - 串行端口编码
- excel - 粘贴导致 VBA 行为不合逻辑
- python - pandas中excel中的匹配索引函数