Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursively delete all JSON keys with null values and delete parent key if all child keys are deleted

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.

like image 613
user125535 Avatar asked Dec 06 '25 18:12

user125535


1 Answers

You need to check if app[key] has keys after you delete null keys.

const x = {
  "applicant": {
    'first_name': null,
    'last_name': null,
    'employment_type': null
  },
  'phone': 1123123,
  'branch': null,
  'industry': {
    'id': 1,
    'name': null
  },
  "status": "333"
}

function isEmpty(obj) {
  for(var key in obj) return false;

  return true
}

function delKeys(app){
  for(var key in app){
    if(app[key] !== null && typeof(app[key]) === 'object'){
      delKeys(app[key])

      if(isEmpty(app[key])) {
        delete app[key]
      }
    } 
    if(app[key] === null){
      delete app[key]
    }
  }
}

delKeys(x)

console.log(x)
like image 89
Yury Tarabanko Avatar answered Dec 08 '25 13:12

Yury Tarabanko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!