Remove empty properties / falsy values from Object

2019-01-30 01:31发布

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?

11条回答
可以哭但决不认输i
2楼-- · 2019-01-30 01:57
Object.keys(o).forEach(function(k) {
    if (!o[k]) {
        delete o[k];
    }
});
查看更多
仙女界的扛把子
3楼-- · 2019-01-30 01:58

for object use delete.

for(var k in obj){

  if(obj.hasOwnProperty(k) && !obj[k]){
    delete obj[k];
  }
}
查看更多
闹够了就滚
4楼-- · 2019-01-30 01:59

in the lodash you do like this:

_.pickBy(object, _.identity);
查看更多
淡お忘
5楼-- · 2019-01-30 02:00

Quick 'n Clear: _.omit( source, i => !i );

This is stated in an inverse fashion to Emil's answer. This way imho reads clearer; it's more self explanatory.

Slightly less clean if you don't have the luxury of ES6: _.omit( source, function(i){return !i;});

Alternate: _.omit( source, _.isEmpty)

Using _.isEmpty, instead of _.identity for truthiness, will also conveniently remove empty arrays and objects from the collection and perhaps inconveniently remove numbers and dates. Thus the outcome is NOT an exact answer to the OP's question, however it could be useful when looking to remove empty collections.

查看更多
老娘就宠你
6楼-- · 2019-01-30 02:04

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;
  }
});
查看更多
登录 后发表回答