搜索对象的内部对象并替换值

时间:2019-06-25 21:05:14

标签: javascript loops object recursion

我想遍历object内部的所有object值,并用 * Restricted * 替换密码值。我想对所有这些项目使用递归方式tp循环

在我定位包含密码值的对象之前,我一直认为它可以出现在对象条目内的其他位置。

这就是我尝试过的

if (entry.requestBody) {
    for (const key of Object.keys(entry.requestBody)) {
      if (key.toLowerCase().includes("password")) {
        entry.requestBody[key] = "***Restricted***"
      }
    }
    if (entry.config._object) {
      for (const key of Object.keys(entry.config._object)) {
        if (key.toLowerCase().includes("password")) {
          entry.config._object[key] = "***Restricted***"
        }
      }
    }
}



{
  "requestBody": {
    "email": "ror@ror.com",
    "password": "asdasdsad"
  },
  "code": "VALIDATION_ERROR",
  "config": {
    "isJoi": true,
    "name": "ValidationError",
    "details": [
      {
        "message": "\"email\" must be a valid email",
        "path": [
          "email"
        ],
        "type": "string.email",
        "context": {
          "value": "ror@ror.com",
          "key": "email",
          "label": "email"
        }
      }
    ],
    "_object": {
      "email": "ror@ror.com",
      "password": "asdasdsad"
    },
    "_meta": {
      "source": "body"
    }
  }
}
}




"requestBody": {
    "email": "ror@ror.com",
    "password": "***Restricted***"
}

1 个答案:

答案 0 :(得分:0)

使用recursion而不是regex来获得快速而肮脏的解决方案:

var bodyString = JSON.stringify(entry.requestBody);

var fixedBodyString = bodyString.replace(/"password":".*"/g, '"password":"***Restricted***"');

var body = JSON.parse(fixedBodyString );

工作示例: https://playcode.io/353673?tabs=script.js,preview,console