如何在JavaScript中用正则映射替换数组对象指定键值内容?
问题描述
我有以下两个变量regexMap和outputMap:
var regexMap = new Map([ ['valOne\\d{6}', 'regexvalue1'], ['valTwo\\d{4}', 'regexvalue2'] ]) var outputMap = [ new CustomObj({ 'key1': 'value1', 'key2': 'value2', 'key3': 'A sentence with valOne123456 and valTwo2345' }), new CustomObj({ 'key1': 'value1', 'key2': 'value2', 'key3': 'A sentence with valTwo1234' }), new CustomObj({ 'key1': 'value1', 'key2': 'value2', 'key3': 'A sentence with value3' }) ]
需要检查outputMap中每个CustomObj的指定键(如key3)的值,若该值匹配regexMap中的任意正则键,则将匹配部分替换为regexMap中对应的映射值,最终得到如下输出:
[ new CustomObj({ 'key1': 'value1', 'key2': 'value2', 'key3': 'A sentence with regexvalue1 and regexvalue2' }), new CustomObj({ 'key1': 'value1', 'key2': 'value2', 'key3': 'A sentence with regexvalue2' }), new CustomObj({ 'key1': 'value1', 'key2': 'value2', 'key3': 'A sentence with value3' }) ]
解决方案
可以通过遍历数组和正则替换来实现需求,分两种场景给出实现代码:
场景1:直接修改原对象
如果CustomObj的属性允许直接修改,可使用以下代码:
// 指定要处理的目标键 const targetKey = 'key3'; // 遍历outputMap中的每个对象 outputMap.forEach(obj => { let str = obj[targetKey]; // 非字符串类型直接跳过 if (typeof str !== 'string') return; // 遍历所有正则规则,执行替换 for (const [regexPattern, replacement] of regexMap) { // 创建带全局标志的正则,确保替换所有匹配项 const regex = new RegExp(regexPattern, 'g'); str = str.replace(regex, replacement); } // 将替换后的结果赋值回原对象 obj[targetKey] = str; });
场景2:创建新对象不修改原数据
如果需要保留原对象,生成新的数组和CustomObj实例:
const targetKey = 'key3'; const processedOutputMap = outputMap.map(obj => { let str = obj[targetKey]; if (typeof str === 'string') { for (const [regexPattern, replacement] of regexMap) { const regex = new RegExp(regexPattern, 'g'); str = str.replace(regex, replacement); } } // 创建新的CustomObj,复制原属性并更新目标键 return new CustomObj({ ...obj, [targetKey]: str }); });
关键说明
- 正则转义修正:原
regexMap中的正则字符串需注意转义,比如\d在JS字符串中要写成\\d,否则会被解析为无效转义字符。 - 全局替换标志:使用
g标志确保同一字符串中所有匹配正则的部分都会被替换,而不仅仅是第一个匹配项。 - 类型校验:增加字符串类型校验,避免非字符串值导致的错误。
内容的提问来源于stack exchange,提问作者code-geek
相关产品推荐
相关产品推荐

