Categories
JavaScript Answers

How to Use Lodash to Find and Return an Object from a JavaScript Array?

Spread the love

Sometimes, we want to use Lodash to find and return an object from a JavaScript array.

In this article, we’ll look at how to use Lodash to find and return an object from a JavaScript array.

Using the find Method

We can use the find method to find an object with a predicate function that returns the condition of the object we’re looking for.

For instance, we can write:

const arr = [{
    description: 'object1',
    id: 1
  },
  {
    description: 'object2',
    id: 2
  },
  {
    description: 'object3',
    id: 3
  },
  {
    description: 'object4',
    id: 4
  }
]

const obj = _.find(arr, (o) => {
  return o.description === 'object3';
});
console.log(obj)

We pass in the array to search as the first argument.

And we pass in the predicate function that returns the condition of the object we’re looking for as the 2nd argument.

Therefore, obj is:

{description: "object3", id: 3}

We can also pass in an object as the 2nd argument to search for an object with the property with the given value:

const arr = [{
    description: 'object1',
    id: 1
  },
  {
    description: 'object2',
    id: 2
  },
  {
    description: 'object3',
    id: 3
  },
  {
    description: 'object4',
    id: 4
  }
]

const obj = _.find(arr, {
  description: 'object3'
});
console.log(obj)

And we can pass in an array with the property key and value to do the same search:

const arr = [{
    description: 'object1',
    id: 1
  },
  {
    description: 'object2',
    id: 2
  },
  {
    description: 'object3',
    id: 3
  },
  {
    description: 'object4',
    id: 4
  }
]

const obj = _.find(arr, ['description', 'object3']);
console.log(obj)

They all get the same result as the first example.

Conclusion

We can use the Lodash find method to find the object with the given condition in an array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *