1

I have a nested object and want to remove all key/value pairs if the value is null or undefined. I've managed to get the below code working but it doesn't check the nested key/value pairs and wondered if someone could help me figure out what needs adding to the code please?

var myObj = {
  fName:'john',
  lName:'doe',
  dob:{
    displayValue: null, 
    value: null
  },
  bbb:null
};

function clean(obj) {
  for (var propName in obj) { 
    if (obj[propName] === null || obj[propName] === undefined || obj[propName] === '') {
      delete obj[propName];
    }
  }
  return obj;
}
console.log(clean(myObj));

The above code does the job to remove 'bbb' and its value and I want the same done for the nested object represented by 'dob' as well.

https://jsbin.com/mudirateso/edit?js,console,output

Any help is greatly appreciated.

2

1 Answer 1

1

You're already almost there. Just have the function recurse if the property is another object:

var myObj = {
  fName:'john',
  lName:'doe',
  dob:{
    displayValue: null, 
    value: null
  },
  bbb:null
};

function clean(obj) {
  for (var propName in obj) { 
    if (obj[propName] === null || obj[propName] === undefined || obj[propName] === '') {
      delete obj[propName];
    } else if (typeof obj[propName] === "object") {
      // Recurse here if the property is another object.
      clean(obj[propName])
    }
  }
  return obj;
}
console.log(clean(myObj));

Sign up to request clarification or add additional context in comments.

2 Comments

But beware of infinite recursion.
Thank you both!! Much appreciated. @CRice

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.