I am in need of creating a function that can scan through a nested JSON structure to locate specific elements and delete all occurrences of those elements, even if they are within an array.
Consider this JSON example:
{
"userId": "John991",
"group1": {
"color": "red",
"height": "100",
"userid": "John992"
},
"data": [
{
"userid": "John993",
"Key3": "Value3"
},
{
"group2": [{
"userid": "John994"
}]
}
],
"Key1": "Value1",
"Key2": "Value2"
}
The desired output should be:
{
"group1": {
"color": "red",
"height": "100"
},
"data": [
{
"Key3": "Value3"
},
{
"group2": [
{}
]
}
],
"Key1": "Value1",
"Key2": "Value2"
}
Thus far I have managed to parse the JSON and remove a specified element if it is found. However, my current code does not handle arrays or nested JSONs. The existing code snippet shown below solely removes instances of "userid":"John991".
var b1 = JSON.parse(JSON);
if (b1.hasOwnProperty("userid")){
delete b1["userid"];
}