How Lodash _.pick Works Under the Hood
In JavaScript, creating subsets of objects is a common task, and
Lodash provides the _.pick utility to handle this
efficiently and immutably. This article explains the internal mechanics
of _.pick, breaking down how it normalizes input paths,
resolves values from a source object, and constructs a brand-new object
containing only the selected properties.
Input Normalization and Flattening
The _.pick function accepts a source object and one or
more property keys, which can be passed as individual strings, symbols,
or arrays of paths. Internally, Lodash first handles argument parsing by
flattening any nested arguments into a single collection of property
paths. If the source object is null or
undefined, the function short-circuits immediately and
returns an empty object.
The Core Implementation:
basePick
Under the hood, _.pick delegates work to an internal
helper named basePick. This function sets up a new, empty
target object ({}) to serve as the destination. Because it
constructs an entirely new object reference rather than deleting
unwanted keys from the input, the operation is completely
non-destructive and guarantees that the original source object remains
immutable.
Path Resolution and Extraction
Lodash iterates through each requested path and performs the following operations:
- Path Parsing: Lodash determines whether the target
key is a simple single-depth property or a deep path (such as
'user.profile.name'or['user', 'profile', 'name']). - Value Retrieval: For simple keys, it checks if the
key exists on the source object. For deep paths, it uses
baseGet, an internal traversal mechanism that walks down the source object's properties step by step, safely handling potentiallyundefinedornullintermediate objects without throwing runtime errors. - Existence Verification: Lodash verifies that the
requested path actually exists in the source object using checks akin to
hasIn. If a path does not exist on the source, it is simply skipped.
Assembling the Output Object
When a property is found, Lodash places the value into the newly
created destination object. For standard keys, it applies a safe
assignment utility like assignValue to bind the key and
value to the root of the new object. If the requested property was a
deep path, Lodash uses its internal baseSet logic to
reconstruct the necessary nested object hierarchy in the destination
object, mirroring the source structure only to the depth required to
hold the selected value.
Once all specified keys and paths have been evaluated,
_.pick returns the accumulated target object, containing
exclusively the requested properties that were present on the
source.