Is there some elegant way of filtering out falsey properties from this object with lodash/underscore? Similar to how _.compact(array)
removes falsey elements fr
You want _.pick
, it takes a function as an argument and returns an object only containing the keys for which that function returns truthy. So you can do:
filtered = _.pick(obj, function(value, key) {return value;})
Or even more succinctly:
filtered = _.pick(obj, _.identity)
Lodash 4.0 split the _.pick
function into _.pick
, which takes an array of properties, and _.pickBy
which takes a function. So now it'd be
filtered = _.pickBy(obj, function(value, key) {return value;})
Or, since _.pickBy
defaults to using _.identity
as it's second argument, it can just be written as:
filtered = _.pickBy(obj);