I have below JSON data with nested objects. I want to delete the ‘id’ from this structure and return the changed JSON from the function. I have tried to do it recursively below way but not able to return the changed JSON.
JavaScript
x
29
29
1
var jsonStr =
2
{"_id":"7r0c0342e",
3
"user":"myuser",
4
"project":"abcd",
5
"info":{"DOMAIN":{"Department":{"profile":[{"workex":8,"name":"alex","id":82838},
6
{"workex":8,"name":"smith","id":84838} ]}}} };
7
8
9
processJSON(jsonStr);
10
11
function processJSON(jsondata) {
12
for (var i in jsondata) {
13
var row = jsondata[i];
14
if(typeof row == "object") {
15
processJSON(row);
16
} else if(typeof row == 'number') {
17
if(i == 'id') {
18
delete jsondata[i];
19
} else {
20
continue;
21
}
22
} else {
23
continue;
24
}
25
}
26
}
27
28
console.log(jsonStr);
29
How can I return the rest of the JSON from the processJSON() and hold that in a variable ? Secondly, is this the correct way to do it recursively ?
Thanks.
Advertisement
Answer
JavaScript
1
30
30
1
var jsonStr =
2
{
3
"_id": "7r0c0342e",
4
"user": "myuser",
5
"project": "data_mining",
6
"info": {
7
"DOMAIN": {
8
"Department": {
9
"profile": [{"workex": 8, "name": "alex", "id": 82838},
10
{"workex": 8, "name": "smith", "id": 84838}]
11
}
12
}
13
}
14
};
15
let modifedJson = JSON.parse(JSON.stringify(jsonStr));
16
17
parseJson = function (json) {
18
for (let key in json) {
19
if (key === 'id') {
20
delete json[key];
21
}
22
else if (typeof json[key] === 'object') {
23
parseJson(json[key])
24
}
25
26
}
27
}
28
parseJson(modifedJson)
29
console.log('modified',modifedJson)
30
console.log('original',jsonStr)