Fuechter Fuechter - 4 months ago 8
Javascript Question

Is there a way delete a deep property with values NULL or UNDEFINED or where object is empty recursively?

Example:

let anyObject = {
name: 'Any name',
address: [{
street: null, // should exclude
city: 'any city',
state: 'any state'
}, {}],
otherObject: {
otherProperty: {
value: {
value1: 1,
value2: {} // should exclude
}
}
}
}

removeAllPropertyWithoutValue(anyObject)


Exist some algorithm efficient for this? I tried with
_.pick
, but is only on first level deep object.

Answer

This should do what you're expecting:

var anyObject = {
  name: 'Any name',
  address: [{
    street: null,
    city: 'any city',
    state: 'any state'
  }, {}],
  otherObject: {
    otherProperty: {
       value: {
         value1: 1,
         value2: {}
       } 
    }
  }
}

function cleanUp(obj) {
  Object.keys(obj).forEach(function(k) {
    if(obj[k] === null || obj[k] === undefined) {
      obj instanceof Array ? obj.splice(k, 1) : delete obj[k];
    }
    else if(typeof obj[k] == 'object') {
      if(Object.keys(obj[k]).length) {
        cleanUp(obj[k]);
      }
      else {
        obj instanceof Array ? obj.splice(k, 1) : delete obj[k];
      }
    }
  });
}

cleanUp(anyObject);
console.log(anyObject);