Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptLodash _.findKey() Method

Lodash _.findKey() Method

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.

javascript




// 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.

javascript




// 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.

javascript




// 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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments