Lodash _.findKey() Method
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, lang, function, objects, numbers etc.
The _.findKey() method is similar to _.find() method except that it returns the key of the first element, predicate returns true for instead of the element itself.
Syntax:
_.findKey(object, predicate)
Parameters: This method accepts two parameters as mentioned above and described below:
- object: It holds the object to inspect every element.
- predicate: It holds the function that the method invoked per iteration.
Return Value: This method returns the key of the matched element else undefined.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
// Requiring the lodash library const _ = require("lodash"); // Original array var users = { 'meetu': { 'salary': 36000, 'active': true }, 'teetu': { 'salary': 40000, 'active': false }, 'seetu': { 'salary': 10000, 'active': true }}; // Using the _.findKey() methodlet found_elem = _.findKey(users, function(o) { return o.salary < 40000; }); // Printing the output console.log(found_elem); |
Output:
meetu
Example 2:
// Requiring the lodash library const _ = require("lodash"); // Original array var users = { 'meetu': { 'salary': 36000, 'active': true }, 'teetu': { 'salary': 40000, 'active': false }, 'seetu': { 'salary': 10000, 'active': true }}; // Using the _.findKey() method// The `_.matches` iteratee shorthandlet found_elem = _.findKey(users, { 'salary': 10000, 'active': true }); // Printing the output console.log(found_elem); |
Output:
seetu
Example 3:
// Requiring the lodash library const _ = require("lodash"); // Original array var users = { 'meetu': { 'salary': 36000, 'active': true }, 'teetu': { 'salary': 40000, 'active': false }, 'seetu': { 'salary': 10000, 'active': true }}; // Using the _.findKey() method// The `_.matchesProperty` iteratee shorthandlet found_elem = _.findKey(users, ['active', false]); // Printing the output console.log(found_elem); |
Output:
teetu
Example 4:
// Requiring the lodash library const _ = require("lodash"); // Original array var users = { 'meetu': { 'salary': 36000, 'active': true }, 'teetu': { 'salary': 40000, 'active': false }, 'seetu': { 'salary': 10000, 'active': true }}; // Using the _.findKey() method// The `_.property` iteratee shorthandlet found_elem = _.findKey(users, 'active'); // Printing the output console.log(found_elem); |
Output:
meetu
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.


.png)