gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:49:24 25 4
gpt4 key购买 nike

我想创建一个函数来检查嵌套 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));

关于javascript - 如何从嵌套 JSON 有效负载 (JavaScript) 中删除特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60102192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com