Finding objects by nested properties is a common task when dealing with complex data structures like deeply nested arrays or objects. Lodash, a popular JavaScript utility library, provides methods that simplify working with deeply nested data.
Prerequisites
Install Lodash:
Open your terminal and navigate to your project directory. Run the following command to install Lodash:
npm install lodashBelow are the approaches to finding objects by Nested Properties with Lodash:
Table of Content
Using Lodash find() method
In this approach we will use the find() method in Lodash this helps us to retrieve the first element in a collection that matches the given condition. Combining it with Lodash’s get allows us to access deeply nested properties without worrying about undefined errors.
Syntax:
_.find(collection, obj => _.get(obj, 'nested.property') === value);Example: In below example we have nested object and we are finding the Object by Nested Properties using Lodash's find method.
const _ = require('lodash');
const users = [
{
id: 1, details: {
name: 'Rohit Sharma',
age: 28
}
},
{
id: 2, details: {
name: 'Yuvraj Singh',
age: 32
}
},
{
id: 3, details: {
name: 'David Warner',
age: 25
}
},
];
const result = _.find(users, user => _.get(user,
'details.age') === 32);
console.log(result);
Output:
{ id: 2, details: { name: 'Yuvraj Singh', age: 32 } }Using Lodash filter() method
In this approach we will use Lodash filter() method. While find returns the first matching element, filter returns all elements that match a condition. We can use Lodash’s get to access nested properties.
Syntax:
_.filter(collection, obj => _.get(obj, 'nested.property') === value);Example: In this example we have nested objct and we will find objects which have age greater than 25 using filter method of lodash.
const _ = require('lodash');
const users = [
{
id: 1, details: {
name: 'Rohit Sharma',
age: 28
}
},
{
id: 2, details: {
name: 'Yuvraj Singh',
age: 32
}
},
{
id: 3, details: {
name: 'David Warner',
age: 25
}
},
{
id: 4, details: {
name: 'Yashaswi Jaiswal',
age: 20
}
},
];
const result = _.filter(users,
user => _.get(user, 'details.age') > 25);
console.log(result);
Output:
[
{ id: 1, details: { name: 'Rohit Sharma', age: 28 } },
{ id: 2, details: { name: 'Yuvraj Singh', age: 32 } }
]