How to use Lodash to find and return an object from an array?

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

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

How to use Lodash to find and return an object from an array?

To use Lodash to find and return an object from an array, we can use the find method.

For instance, we write:

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

const id = 3
const song = _.find(songs, {
  id
});
console.log(song)

We call find with the array we’re searching and the property value of each object we’re searching for.

Therefore, we get that song is {description: 'object3', id: 3} since we’re looking for the entry with id 3.

Conclusion

To use Lodash to find and return an object from an array, we can use the find method.