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?
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?
for object use delete.
in the lodash you do like this:
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.You could make your own underscore plugin (mixin) :
And then use it as a native underscore method :
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: