Skip to content

pickBy

Creates a new object with only the own enumerable entries for which predicate returns true.

Complements pick for when the keys to keep aren’t known ahead of time — pick takes an explicit key list, pickBy takes a predicate.

Available since v3.0.0

import { pickBy } from '@helpers4/object';
// or, from the all-in-one package (same code, one install):
import { pickBy } from 'helpers4/object';
pickBy<T extends Record<string, unknown>>(obj: T | null | undefined, predicate: function): Partial<T> | null | undefined
ParameterTypeDescription
objT | null | undefinedThe source object. `null`/`undefined` pass through unchanged.
predicatefunctionCalled with `(value, key)` for each own enumerable entry

Partial<T> | null | undefined — A new object with only the matching entries

Unlike pick(), the keys to keep don’t need to be known ahead of time.

pickBy({ a: 1, b: 0, c: 2 }, (value) => value > 0)
// => { a: 1, c: 2 }

The predicate also receives the key, so filtering by name works too.

pickBy({ _id: 1, name: 'x', _internal: true }, (_v, key) => !key.startsWith('_'))
// => { name: 'x' }

View source on GitHub