Lodash _.findKey() method is similar to the _.find() method except that it returns the key of the first element, and the predicate returns true instead of the element itself.
Syntax:
_.findKey(object, [predicate])Parameters:
- object(Object) holds the object to inspect every element.
- predicate(Function) holds the function that the method invoked per iteration.
Return Value:
This method returns the key of the matched element else undefined.
Example 1: In this example, we are getting a key whose salary is less than '4000' by the use of the _.findKey() method.
// Requiring the lodash library
const _ = require("lodash");
// Original array
let users = {
'meetu': { 'salary': 36000, 'active': true },
'teetu': { 'salary': 40000, 'active': false },
'seetu': { 'salary': 10000, 'active': true }
};
// Using the _.findKey() method
let found_elem =
_.findKey(users, function (o) { return o.salary < 40000; });
// Printing the output
console.log(found_elem);
Output:
meetu
Example 2: In this example, we are getting a key by passing an object that will validate if t matches that 'users' condition or not by the use of the _.findKey() method.
// Requiring the lodash library
const _ = require("lodash");
// Original array
let users = {
'meetu': { 'salary': 36000, 'active': true },
'teetu': { 'salary': 40000, 'active': false },
'seetu': { 'salary': 10000, 'active': true }
};
// Using the _.findKey() method
// The `_.matches` iteratee shorthand
let found_elem = _.findKey(users, {
'salary': 10000,
'active': true
});
// Printing the output
console.log(found_elem);
Output:
seetu
Example 3: In this example, we are getting a key by passing an array that will validate if t matches that 'users' condition or not by the use of the _.findKey() method.
// Requiring the lodash library
const _ = require("lodash");
// Original array
let users = {
'meetu': { 'salary': 36000, 'active': true },
'teetu': { 'salary': 40000, 'active': false },
'seetu': { 'salary': 10000, 'active': true }
};
// Using the _.findKey() method
// The `_.matchesProperty` iteratee shorthand
let found_elem = _.findKey(users, ['active', false]);
// Printing the output
console.log(found_elem);
Output:
teetu