在嵌套对象中搜索键并删除它们

2023-12-03

我需要从对象中删除某些键,前提是这些键包含在我的“deleteKeys”数组中。

我怎样才能以优化的方式实现这一目标?

这是代码:

const data = {
  "details": [{
    "userId": "user01",
    "documents": [{
      "document": {
        "id": "doc_pp_01",
        "type": "pp",
        "number": "222333444",
        "personName": {
          "first": "JAMES",
          "middle": "JOHNIE",
          "last": "SMITH"
        },
        "nationality": "AL",
        "dateOfBirth": "1990-01-01",
        "issuingCountry": "AL",
        "expiryDate": "2025-01-01",
        "gender": "MALE"
      }
    }]
  }],
  "criteria": {
    "id:": "AB1234",
    "fullName": "James Johnie Smith"
  }
};
const deleteKeys = ["details", "fullName"];

function cleanData(data) {
  for (let elem in data) {
    if (deleteKeys.includes(elem)) {
      delete data[elem];
    }
  }
  return data;
}

console.log(cleanData(data));

预期输出:

{
  "criteria": {
    "id:": "AB1234"
  }
};

我想知道是否可以通过对对象进行字符串化来实现这一点,因为这将是一个更干净的解决方案。

function assignKey(data) {
  const formattedData = JSON.stringify(data);
  deleteKeys.forEach(function(elem) {
    if (formattedData.includes(elem)) {
      formattedData.replace(elem, '');
    }
  });
  return JSON.parse(formattedData);
}

使用时出现的问题delete是你本质上改变了原始对象。如果您在不同位置使用相同的对象引用,这可能会导致问题。

JSON 方法将不起作用,因为删除部分字符串后生成的 JSON 字符串无效。你可以做到这一点,但更容易出错。

我总是喜欢让这种函数返回对象的新实例。

function removeKeys(obj, keys) {
  if (Array.isArray(obj)) return obj.map(item => removeKeys(item, keys));

  if (typeof obj === 'object' && obj !== null) {
    return Object.keys(obj).reduce((previousValue, key) => {
      return keys.includes(key) ? previousValue : { ...previousValue, [key]: removeKeys(obj[key], keys) };
    }, {});
  }

  return obj;
}

也可以先浅复制对象并使用delete在新对象上而不是使用reduce.

function removeKeys(obj, keys) {
  if (Array.isArray(obj)) return obj.map((item) => removeKeys(item, keys));

  if (typeof obj === "object" && obj !== null) {
    return Object.keys(obj).reduce((previousValue, key) => {
      return keys.includes(key)
        ? previousValue
        : { ...previousValue, [key]: removeKeys(obj[key], keys) };
    }, {});
  }

  return obj;
}

const data = {
  details: [
    {
      userId: "user01",
      documents: [
        {
          document: {
            id: "doc_pp_01",
            type: "pp",
            number: "222333444",
            personName: {
              first: "JAMES",
              middle: "JOHNIE",
              last: "SMITH"
            },
            nationality: "AL",
            dateOfBirth: "1990-01-01",
            issuingCountry: "AL",
            expiryDate: "2025-01-01",
            gender: "MALE"
          }
        }
      ]
    }
  ],
  criteria: {
    "id:": "AB1234",
    fullName: "James Johnie Smith"
  }
};

console.log(
  "Without `fullName` and `details`",
  removeKeys(data, ["fullName", "details"])
);
console.log("Without `id:` and `gender`", removeKeys(data, ["id:", "gender"]));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在嵌套对象中搜索键并删除它们 的相关文章

随机推荐