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.
const _ = require( "lodash" );
var users = {
'meetu' : { 'salary' : 36000, 'active' : true },
'teetu' : { 'salary' : 40000, 'active' : false },
'seetu' : { 'salary' : 10000, 'active' : true }
};
let found_elem = _.findKey(users, function (o) { return
o.salary < 40000; });
console.log(found_elem);
|
Output:
meetu
Example 2:
const _ = require( "lodash" );
var users = {
'meetu' : { 'salary' : 36000, 'active' : true },
'teetu' : { 'salary' : 40000, 'active' : false },
'seetu' : { 'salary' : 10000, 'active' : true }
};
let found_elem = _.findKey(users, { 'salary' : 10000,
'active' : true });
console.log(found_elem);
|
Output:
seetu
Example 3:
const _ = require( "lodash" );
var users = {
'meetu' : { 'salary' : 36000, 'active' : true },
'teetu' : { 'salary' : 40000, 'active' : false },
'seetu' : { 'salary' : 10000, 'active' : true }
};
let found_elem = _.findKey(users, [ 'active' , false ]);
console.log(found_elem);
|
Output:
teetu
Example 4:
const _ = require( "lodash" );
var users = {
'meetu' : { 'salary' : 36000, 'active' : true },
'teetu' : { 'salary' : 40000, 'active' : false },
'seetu' : { 'salary' : 10000, 'active' : true }
};
let found_elem = _.findKey(users, 'active' );
console.log(found_elem);
|
Output:
meetu
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.