What Does Lodash findKey Return on Success?
The Lodash _.findKey method is a utility function used
to search through an object's properties and identify an entry that
satisfies a specific condition. This article explains the exact return
value of _.findKey upon successfully locating a property,
how it behaves during execution, and how it differs from related search
methods in the Lodash library.
When _.findKey successfully locates a property that
satisfies the provided predicate function, it returns the
key of that property as a string.
Unlike _.find, which returns the resolved value
of the matching property, _.findKey specifically returns
the property name (the key identifier) associated with that
value.
How It Works
The method iterates over the own enumerable string keyed properties of an object, executing the predicate function for each property until the predicate returns truthy. Once a match is found, iteration immediately halts, and the string key of the first matching element is returned.
Consider the following example:
const users = {
'user_101': { name: 'Alice', active: false },
'user_102': { name: 'Bob', active: true },
'user_103': { name: 'Charlie', active: true }
};
const result = _.findKey(users, (user) => user.active);
console.log(result);
// Output: 'user_102'In this example, even though both 'user_102' and
'user_103' satisfy the condition
user.active === true, _.findKey stops
evaluating at the first match and returns the string
'user_102'.
Shorthand Predicate Syntax
_.findKey also supports Lodash's shorthand syntaxes for
properties and values, continuing to return the string key when a match
is verified:
// Matches property value using object shorthand
const resultByObject = _.findKey(users, { name: 'Charlie' });
// Output: 'user_103'
// Matches truthiness of a property path
const resultByProperty = _.findKey(users, 'active');
// Output: 'user_102'If no element satisfies the predicate, or if the target object is
empty, null, or undefined, the method returns
undefined.