![]() |
VOOZH | about |
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.
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
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.
_.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.
Output:
{ id: 2, details: { name: 'Yuvraj Singh', age: 32 } }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.
_.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.
Output:
[
{ id: 1, details: { name: 'Rohit Sharma', age: 28 } },
{ id: 2, details: { name: 'Yuvraj Singh', age: 32 } }
]