You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS遍历对象按数组内正则规则替换属性值失败如何解决

问题分析

  • 你用forEach遍历Object.values()拿到的是属性值的副本,字符串、数字等基本类型是按值传递的,循环内修改临时变量val根本不会写回原对象的对应属性,修改完全不生效。
  • 原对象存在嵌套结构(secondKey是子对象),当前代码只处理了第一层属性,没有递归遍历嵌套对象,而且直接对子对象调用toString()会得到无意义的[object Object],无法处理子对象内的属性值。
  • 当前逻辑直接修改传入的原对象,会污染原始的event变量,如果后续还有使用原对象的需求会出错。

修复后代码

let event = {
  "firstKey":"1",
  "secondKey": {
    "a":"one",
    "b":"two",
    "c":"three"
  },
  "id":111934444,
  "count":1,
  "location":"https://www-domain-org/username=steven&tel=1234",
  "title":"lastname=hey",
  "sd":"24-bit"
};
    
let myReg = [
  {
    name: 'telephone',
    reg: /((tel=)|(telephone=))[\d\+\s][^&\/\?]+/gi,
    group: '$1'
  },
  {
    name: 'names',
    reg: /((username=)|(lastname=))[^&\/\?]+/gi,
    group: '$1'
  }
];
    
let secret = function(obj){
  // 浅拷贝外层对象,避免污染原对象,嵌套对象会递归处理
  const processed = {...obj};
  // 遍历对象键,才能把修改后的值写回对应属性
  Object.keys(processed).forEach(key => {
    const val = processed[key];
    // 值为普通对象时递归处理
    if(typeof val === 'object' && val !== null && !Array.isArray(val)){
      processed[key] = secret(val);
      return;
    }
    // 非对象类型做正则替换
    let strVal = val.toString();
    myReg.forEach(regTest => {
      strVal = strVal.replace(regTest.reg, regTest.group + '[redacted ' + regTest.name + ']');
    });
    processed[key] = strVal;
  })
  return processed;
}

let newEvent = secret(event);
console.log(newEvent);
// 原event对象不会被修改
console.log(event);

运行效果说明

替换后核心属性值符合预期:

  • location 变为 https://www-domain-org/username=[redacted names]&tel=[redacted telephone]
  • title 变为 lastname=[redacted names]
  • 其他无匹配规则的属性值保持不变,嵌套对象结构完整保留

内容的提问来源于stack exchange,提问作者rimed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:36:01