Sunday, May 19, 2024
132
rated 0 times [  136] [ 4]  / answers: 1 / hits: 61410  / 9 Years ago, thu, march 26, 2015, 12:00:00

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,
}

More From » underscore.js

 Answers
164

Lodash 4.0


Lodash 4.0 has _.pick, which takes an array of properties, and _.pickBy which takes a function as an argument and returns an object only containing the keys for which that function returns truthy which is what we want here, so it'd be:


filtered = _.pickBy(obj, function(value, key) {return value;})

Or, since _.pickBy defaults to using _.identity as it's second argument, (and that's essentially what we've written above,) it can just be written as:


filtered = _.pickBy(obj);

Underscore or Lodash prior to version 4.0


In underscore and old versions of lodash, there's just a single _.pick, which has both behaviors of _.pick and _.pickWith from v4. So you can do:


filtered = _.pick(obj, function(value, key) {return value;})

Or more succinctly:


filtered = _.pick(obj, _.identity)

[#67303] Tuesday, March 24, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deonkalvinw

Total Points: 409
Total Questions: 96
Total Answers: 89

Location: Saint Pierre and Miquelon
Member since Sun, Nov 27, 2022
2 Years ago
deonkalvinw questions
Sun, Feb 6, 22, 00:00, 2 Years ago
Tue, Dec 28, 21, 00:00, 2 Years ago
Sun, Aug 22, 21, 00:00, 3 Years ago
Sun, Mar 7, 21, 00:00, 3 Years ago
;