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?
You can create a shallow clone:
With lodash's transform,
To add to gion_13's answer:
This one creates a new object and adds keys and values instead of cloning everything and deleting key-value pairs. Minor difference.
But more importantly, checks explicitly for null and undefined instead of falsey, which will delete key-value pairs that have false as a value.
Since Underscore version 1.7.0, you can use
_.pick
:Explanation
The second parameter to
_.pick
can be a predicate function for selecting values. Values for which the predicate returns truthy are picked, and values for which the predicate returns falsy are ignored._.identity
is a helper function that returns its first argument, which means it also works as a predicate function that selects truthy values and rejects falsy ones. The Underscore library also comes with a bunch of other predicates, for instance_.pick(sourceObj, _.isBoolean)
would retain only boolean properties.If you use this technique a lot, you might want to make it a bit more expressive:
Underscore version 1.6.0 provided
_.pick
as well, but it didn't accept a predicate function instead of a whitelist.Suddenly I needed create a function to remove recursively falsies. I hope this helps. I'm using Lodash.
Then you can use it:
Although
_.compact
is documented for use in arrays. It seems to work for objects too. I just ran the following in chrome, opera and firefox consoles:UPDATE: As the sample indicates calling
_.compact
on an object will drop the keys and return a compacted array.