5

Find Objects by Nested Properties with Lodash

 2 years ago
source link: https://masteringjs.io/tutorials/lodash/find-nested-object
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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');

More Lodash Tutorials


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK