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:

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:

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:

  1. Explicit Boolean Returns: If your function returns explicit boolean expressions, such as value > 10 or typeof value === 'string', the expression evaluates directly to true or false.
  2. 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 true and include the key.
  3. Compound Boolean Logic: You can use standard logical operators (&&, ||, !) inside the predicate to evaluate both the value and the key arguments 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 } }