Open In App

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:

Run the command to install Loadsh:

npm i loadash

Using _.find()

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 }

Using _.findIndex() and _.nth()

This approach uses two methods: _.findIndex() to find the index of the first object in an array that satisfies the condition and Lodash's to retrieve the object at a specific index.

Syntax:

_.findIndex(array, [predicate=_.identity], fromIndex);
_.nth(array, n);

Example: The example below shows how to use Lodash to Find and Return an Object from Array Using _.findIndex() and _.nth().

const _ = require('lodash');
const products = [
    { name: 'Headphones', price: 99.99 },
    { name: 'Laptop', price: 799.99 },
    { name: 'Mouse', price: 24.99 },
];

const laptopIndex = _.findIndex(products, 
                        product => product.name === 'Laptop');
if (laptopIndex !== -1) {
    const laptop = _.nth(products, laptopIndex);
    console.log(laptop);
}

Output:

{ name: 'Laptop', price: 799.99 }

Using _.filter()

The _.filter() method extract objects from the "orders" array where the "status" property equals 'pending'. It returns an array containing the filtered objects, representing pending orders.

Syntax:

_.filter( collection, predicate )

Example: The example below shows how to use Lodash to Find and Return an Object from Array Using _.filter().

const _ = require('lodash');
const orders = [
    { id: 1, status: 'pending' },
    { id: 2, status: 'shipped' },
    { id: 3, status: 'pending' },
];

const pendingOrders = _.filter(orders,
    order => order.status === 'pending');
console.log(pendingOrders);

Output:

 [{ id: 1, status: 'pending' }, { id: 3, status: 'pending' }]

Choosing the Right Method

Article Tags :