How to use _.find() In Lodash
The _.find() is ideal for locating the first object in an array that satisfies a specific condition. It iterates through the array and returns the initial matching object. You can define the condition using a callback function or an object with key-value pairs representing the target object’s properties.
Syntax:
_.find(collection, predicate, [fromIndex=0])
Example: The example below shows how to use Lodash to Find and Return an Object from Array Using _.find() method.
const _ = require('lodash');
const customers = [
{ id: 1, name: 'Alice', active: true },
{ id: 2, name: 'Bob', active: false },
{ id: 3, name: 'Charlie', active: true },
];
// Using a callback function
const activeCustomer = _.find(customers,
customer => customer.active);
console.log(activeCustomer);
// Using an object
const customerWithId2 = _.find(customers, { id: 2 });
console.log(customerWithId2);
Output:
{ id: 1, name: 'Alice', active: true }
{ id: 2, name: 'Bob', active: false }
How to use Lodash to Find & Return an Object from Array ?
JavaScript’s built-in array methods offer basic functionality whereas Lodash, a popular utility library, empowers developers with robust tools for complex array operations.
Below are the methods to find and return an object from array using Lodash:
Table of Content
- Using _.find()
- Using _.findIndex() and _.nth()
- Using _.filter()
Run the command to install Loadsh:
npm i loadash
Contact Us