How Lodash _.pick Handles Symbol Property Keys
This article provides a comprehensive overview of how the Lodash
_.pick function processes JavaScript Symbol
primitives when used as object property keys. It covers the mechanics of
passing symbol references, how Lodash's internal path resolution
evaluates symbols, and the practical distinctions between picking symbol
keys explicitly versus relying on key enumeration.
Explicit Symbol References
In JavaScript, Symbol values represent unique,
non-string property keys. The Lodash _.pick utility
supports picking properties identified by symbols, provided that the
exact symbol reference is explicitly passed as an argument.
Because symbols are unique and cannot be coerced automatically from
strings, you cannot select a symbol-keyed property using its string
description (e.g., passing "id" will not retrieve a
property keyed by Symbol('id')). Instead, you must supply
the original Symbol instance:
const idSymbol = Symbol('id');
const user = {
[idSymbol]: 101,
username: 'johndoe',
role: 'admin'
};
// Explicitly pass the symbol reference
const result = _.pick(user, [idSymbol, 'username']);
// result contains: { [Symbol(id)]: 101, username: 'johndoe' }Internal Key Handling
Lodash utilizes an internal check (isKey) to determine
whether an argument should be treated as a direct property identifier or
decomposed into a deep property path (such as
"user.profile.name").
When a Symbol is provided to _.pick:
- Lodash identifies its type as a primitive
Symbol. - It bypasses string-based path parsing logic (such as string splitting or dot-notation traversal).
- It performs a direct property lookup on the source object using the symbol reference.
- If the key exists on the source object (including along its prototype chain), it assigns the property and its corresponding value to the newly returned object using standard bracket notation.
Contrast with Enumeration
and _.pickBy
A common source of confusion is the difference between explicit
picking with _.pick and predicate-based picking with
_.pickBy.
While _.pick can extract symbols because the keys are
explicitly specified by the developer, _.pickBy relies on
internal iteration mechanisms equivalent to Object.keys()
or for...in loops. Standard object iteration ignores
non-enumerable properties and symbol keys (which require
Object.getOwnPropertySymbols). Consequently,
_.pickBy will not iterate over symbol-keyed properties,
making _.pick with an explicit key array the standard
method for extracting symbol-keyed values from an object using
Lodash.