user3598395 user3598395 - 7 months ago 10
Javascript Question

Filtering object properties based on value

Is there some elegant way of filtering out falsey properties from this object with lodash/underscore? Similar to how

_.compact(array)
removes falsey elements from arrays

so from

{
propA: true,
propB: true,
propC: false,
propD: true,
}


returning

{
propA: true,
propB: true,
propD: true,
}

Answer

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)
Comments