0

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.

Fuechter
  • 1,200
  • 2
  • 10
  • 27
  • Have you tried filter? – Jorawar Singh Aug 04 '16 at 16:45
  • 1
    your question says "null or undefined", but you have `value2: {} // should exclude`, can you explain in more detail what values you want to keep? – Rob M. Aug 04 '16 at 16:46
  • 1
    Possible duplicate of [Remove some property levels in deep object hierarchy](http://stackoverflow.com/questions/21158735/remove-some-property-levels-in-deep-object-hierarchy) – Patrick Motard Aug 04 '16 at 16:46
  • Yes, you can. Read this: http://stackoverflow.com/questions/286141/remove-blank-attributes-from-an-object-in-javascript –  Aug 04 '16 at 16:54
  • This is actually slightly more complicated than the above questions, as it is a mix of objects and arrays. It requires either `splice()` or `delete` depending on the current position in the structure. – Arnauld Aug 04 '16 at 17:25
  • Why do you want to exclude `value2: {}` but not `[,{}]`? – Oriol Aug 04 '16 at 17:28

1 Answers1

3

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).reverse().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') {
      cleanUp(obj[k]);

      if(Object.keys(obj[k]).length == 0) {
        obj instanceof Array ? obj.splice(k, 1) : delete obj[k];
      }
    }
  });
}

cleanUp(anyObject);
console.log(anyObject);
Arnauld
  • 5,847
  • 2
  • 15
  • 32