I'm trying to recursively delete null values in a JSON object and all Subobjects. If the subobjects keys are all deleted, then I want that subobject to be deleted as well.
ie.
x = {
"applicant": {
'first_name': null,
'last_name': null,
'employment_type': null
},
'phone': 1123123,
'branch': null,
'industry': {
'id': 1,
'name': null
},
"status": "333"
}
should turn into this:
x = {
'phone': 1123123,
'industry': {
"id": 1
},
"status": "333"
}
Here is the function that I wrote to delete all keys with null values:
function delKeys(app){
for(key in app){
if(app[key] !== null && typeof(app[key]) === 'object'){
delKeys(app[key])
}
if(app[key] === null){
delete app[key]
}
}
But this doesn't delete the parent key with no children:
so instead of the result above, I get this:
x = {
"applicant":{},
"phone":1123123,
"industry":{
'id': 1
}
"status": "333"
}
As you can see, it doesn't delete the applicant key. How would I check for that within the function? or does it need to be written in a separate function that I call AFTER calling delKeys()?
Also, does anyone see this hitting maximum recursion depth? I've tried with bigger JSON objects and it seems to be hitting max recursion depth. I would really appreciate help with debugging that
thank you.