如何从嵌套的 JSON 有效负载 (JavaScript) 中删除特定元素?



我想创建一个函数,该函数将检查嵌套的JSON中的特定元素,如果找到,则删除该元素的所有实例,即使在数组中找到也是如此。

例如,假设我有一个 JSON:

{
"userId": "John991",
"group1": {
"color": "red",
"height": "100",
"userid": "John992"
},
"data": [
{
"userid": "John993",
"Key3": "Value3"
},
{
"group2": [{
"userid": "John994"
}]
}
],
"Key1": "Value1",
"Key2": "Value2"
}

我希望我的结果是

{
"group1": {
"color": "red",
"height": "100"
},
"data": [
{
"Key3": "Value3"
},
{
"group2": [
{}
]
}
],
"Key1": "Value1",
"Key2": "Value2"
}

我能做的最好的事情就是解析 JSON,并删除元素(如果存在(。但是,这不会考虑数组或嵌套的 JSON。下面的代码只删除了"userid":"John991"。

var b1 = JSON.parse(JSON);
if (b1.hasOwnProperty("userid")){
delete b1["userid"];
}

您可以创建一个函数来迭代键并在递归中删除键。像这样的东西

const input = {
"userId": "John991",
"group1": {
"color": "red",
"height": "100",
"userid": "John992"
},
"data": [
{
"userid": "John993",
"Key3": "Value3"
},
{
"group2": [{
"userid": "John994"
}]
}
],
"Key1": "Value1",
"Key2": "Value2"
};
function deleteKey(obj, keyToDelete) {
Object.keys(obj).forEach(key => {
if (key.toLowerCase() === keyToDelete) {
delete obj[key];
}
value = obj[key];
if (value instanceof Object) {
deleteKey(value, keyToDelete);
}
});
}
deleteKey(input, "userid");
console.log(JSON.stringify(input, null, 2));

此函数执行您想要的操作:

const json = {
"userId": "John991",
"group1": {
"color": "red",
"userid": "John992",
"height": "100"
},
"data": [{
"userid": "John993",
"Key3": "Value3"
},
{
"group2": [{
"userid": "John994"
}]
}
],
"Key1": "Value1",
"Key2": "Value2"
}
function objWithout(obj, property) {
let json = JSON.stringify(obj);
const regex = new RegExp(`,?"${property}":".*?",?`, "gi");
json = json.replace(regex, '');
json = json.replace(/""/, '","');
return JSON.parse(json);
}
const result = objWithout(json, "userId")
console.log(result)

该函数objWithout字符串化提供的对象,执行文本替换并返回从编辑的文本解析的对象。文本替换会搜索property的所有实例,无论它出现在对象中的哪个位置,因此userId如果它恰好出现在作为所提供对象成员的对象中,它仍会被替换。

正则表达式替换属性的所有实例及其值以及任何前导和尾随,。在第二步中,如果属性位于其他两个属性的中间,则再次添加,,例如{"a":"b","userId":"user123","c":"d"}.

文本替换由正则表达式完成。您可以在此处阅读有关这些内容的更多信息 https://regexr.com/.

此外,我添加了/i/标志,因为您的对象具有"userId"和"userid",但我认为您希望两者都消失。

最新更新