Lodash pickBy Boolean Logic Explained
This article explains the boolean evaluation logic used by the Lodash
_.pickBy method to filter and construct objects. You will
learn how the function evaluates predicate return values using
JavaScript truthiness, how the default _.identity predicate
functions, and how to control property selection using custom boolean
criteria.
Truthy Evaluation Logic
The _.pickBy method creates a new object composed of
properties from the source object that satisfy a provided predicate
function. The boolean logic governing property inclusion is based
entirely on JavaScript truthiness.
When _.pickBy(object, [predicate=_.identity]) iterates
over an object, it invokes the predicate for each key-value pair:
predicate(value, key)The returned result of this predicate is coerced into a boolean:
- Included: If the predicate returns a
truthy value (any value that evaluates to
truein a boolean context), the property is copied to the new object. - Excluded: If the predicate returns a
falsy value (
false,null,undefined,0,-0,0n,NaN, or""), the property is omitted from the resulting object.
The Default Predicate:
_.identity
When no predicate function is explicitly provided, Lodash defaults to
using _.identity. The _.identity function
simply returns the first argument it receives, which is the property's
value.
Under this default behavior:
- If the property value itself is truthy (e.g., non-empty strings,
numbers other than 0, objects, arrays,
true), the property is preserved. - If the property value is falsy (e.g.,
0,"",null,undefined,false), the property is removed.
const source = { a: 1, b: 0, c: '', d: 'hello', e: null };
const result = _.pickBy(source);
// Result: { a: 1, d: 'hello' }Custom Predicate Logic
When supplying a custom predicate, the logic relies strictly on what your function returns:
- Explicit Boolean Returns: If your function returns
explicit boolean expressions, such as
value > 10ortypeof value === 'string', the expression evaluates directly totrueorfalse. - Implicit Truthy Returns: If your function returns
non-boolean values, Lodash converts them implicitly. For instance,
returning a matching object, non-zero number, or non-empty string will
evaluate to
trueand include the key. - Compound Boolean Logic: You can use standard
logical operators (
&&,||,!) inside the predicate to evaluate both thevalueand thekeyarguments before returning a final truthy or falsy result.
const users = {
alice: { active: true, age: 25 },
bob: { active: false, age: 30 },
charlie: { active: true, age: 17 }
};
// Logical AND evaluation: must be active AND over 18
const activeAdults = _.pickBy(users, (user) => user.active && user.age >= 18);
// Result: { alice: { active: true, age: 25 } }