Search code examples
javascriptarraysobjectunderscore.js

Remove empty properties / falsy values from Object with Underscore.js


I have an object with several properties. I would like to remove any properties that have falsy values.

This can be achieved with compact on arrays, but what about objects?


Solution

  • You could make your own underscore plugin (mixin) :

    _.mixin({
      compactObject: function(o) {
        _.each(o, function(v, k) {
          if(!v) {
            delete o[k];
          }
        });
        return o;
      }
    });
    

    And then use it as a native underscore method :

    var o = _.compactObject({
      foo: 'bar',
      a: 0,
      b: false,
      c: '',
      d: null,
      e: undefined
    });
    

    Update

    As @AndreiNeculau pointed out, this mixin affects the original object, while the original compact underscore method returns a copy of the array.
    To solve this issue and make our compactObject behave more like it's cousin, here's a minor update:

    _.mixin({
      compactObject : function(o) {
         var clone = _.clone(o);
         _.each(clone, function(v, k) {
           if(!v) {
             delete clone[k];
           }
         });
         return clone;
      }
    });