Syntax, Parameter and Return Value
Syntax:
_.findKey(object, [predicate=_.identity])
Parameters:
-
object (Object): The object to inspect.
- [predicate=_.identity] (Function): The function invoked per iteration.
Return Value:
(string|undefined) - Returns the key of the matched element, else undefined.
Examples
Finding a Key Based on a Property Value:
JavaScript
var _ = require('lodash');
var users = {
'barney': { 'age': 36, 'active': true },
'fred': { 'age': 40, 'active': false },
'pebbles': { 'age': 1, 'active': true }
};
var key = _.findKey(users, function(o) { return o.age < 40; });
console.log(key);

You can also try this code with Online Javascript Compiler
Run Code
Output:
'barney'
Demonstrates finding the key of a user whose age is less than 40.
Using a Shorthand with Property Value:
JavaScript
var key = _.findKey(users, { 'age': 1, 'active': true });
console.log(key);

You can also try this code with Online Javascript Compiler
Run Code
Output:
'pebbles'
Shows how to use object literal shorthand to find a key.
Using a Property Name Shorthand:
JavaScript
var key = _.findKey(users, 'active');
console.log(key);

You can also try this code with Online Javascript Compiler
Run Code
Output:
'barney'
An example of using property name shorthand to find the key of the first active user.
Matching Against a Property Value:
JavaScript
var key = _.findKey(users, ['active', false]);
console.log(key);

You can also try this code with Online Javascript Compiler
Run Code
Output:
'fred'
Demonstrates finding the key of a user where the 'active' property is false.
Frequently Asked Questions
How does _.findKey() differ from _.find()?
_.find() returns the value of the first element in a collection that satisfies the predicate, while _.findKey() returns the key of the first property in an object that satisfies the predicate.
What happens if no element satisfies the predicate?
If no element satisfies the predicate, _.findKey() returns undefined.
Can _.findKey() be used with arrays?
While _.findKey() is primarily designed for objects, it can technically be used with arrays. However, the keys in arrays are their indices, so it's more common to use array-specific methods like _.find() for arrays.
Conclusion
Lodash's _.findKey() method offers an efficient and readable way to search for a key in an object based on a condition defined by a predicate function. It is particularly useful for objects with numerous or complex properties where a key needs to be located based on specific criteria.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.