CARVIEW |
Select Language
HTTP/2 200
accept-ranges: bytes
age: 1
cache-control: public,max-age=0,must-revalidate
cache-status: "Netlify Edge"; fwd=miss
content-encoding: gzip
content-type: text/html; charset=UTF-8
date: Wed, 15 Oct 2025 03:58:26 GMT
etag: "913f7decf36a01aa1b226a56a5619f2d-ssl-df"
server: Netlify
strict-transport-security: max-age=31536000
vary: Accept-Encoding
x-nf-request-id: 01K7K09TP894K4CHG8RWGV4SET
Find Objects by Nested Properties with Lodash - Mastering JS
Find Objects by Nested Properties with Lodash
Jun 22, 2022
If you need to search for a nested object, you can use Lodash's .find()
function.
It takes three arguments:
collection
: which can be either an array or object.predicate
: the callback function that Lodash calls on every element in the array.fromIndex
: the index to search from. Defaults to 0.
Lodash will return the first element for which predicate
returns a truthy value, or undefined
if there's no such element.
You can write a predicate
that checks whether an element has a certain nested property.
The following code finds objects by the name.first
property.
const _ = require('lodash');
const obj = [
{
name: {
first: 'Test',
last: 'Testerson'
},
age: 2,
location: 'Florida'
},
{
name: {
first: 'Obi-wan',
last: 'Kenobi'
},
age: 45,
location: 'Tatooine'
},
{
name: {
first: 'Masteringjs',
last: '.io'
},
age: 5,
location: 'Florida'
}
];
let result = _.find(obj, el => el.name.first === 'Test');
result; // { name: { first: 'Test', last: 'Testerson', age: 2 }, location: 'Florida' }
result = _.find(obj, el => el.name.first === 'something else');
result; // undefined
To avoid cases where el.name
is null
or undefined
, you can use optional chaining ?.
, or Lodash's get()
function.
let result = _.find(obj, el => el?.name?.first === 'Test');
// Equivalent:
result = _.find(obj, el => _.get(el, 'name.first') === 'Test');
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!