javascript-lodashHow do I use Lodash to find an object in an array of JavaScript objects?
Using Lodash to find an object in an array of JavaScript objects is simple and straightforward. The following example code block shows how to use Lodash's _.find
method to find an object in an array of JavaScript objects:
const users = [{
'user': 'barney',
'age': 36
}, {
'user': 'fred',
'age': 40
}, {
'user': 'pebbles',
'age': 1
}];
const user = _.find(users, { 'age': 36 });
console.log(user);
Output example
{
'user': 'barney',
'age': 36
}
The code above first creates an array of JavaScript objects called users
and then uses Lodash's _.find
method to find an object that has an age
property with the value of 36. The _.find
method returns the first object in the array that matches the criteria, and in this case it returns the object with user
property set to barney
and age
property set to 36.
Code explanation
const users = [{...}, {...}, {...}];
- creates an array of JavaScript objects calledusers
const user = _.find(users, { 'age': 36 });
- uses Lodash's_.find
method to find an object with anage
property set to 36console.log(user);
- prints the found object to the console
Helpful links
- Lodash documentation: https://lodash.com/docs/4.17.15
_.find
method documentation: https://lodash.com/docs/4.17.15#find
More of Javascript Lodash
- How do I use Lodash in a JavaScript playground?
- How do lodash and underscore differ in JavaScript?
- How do I use Lodash to truncate a string in JavaScript?
- How can I use Lodash to find the unique key of a JavaScript object?
- How can I use Lodash to create a unique array in JavaScript?
- How can I use Lodash's reject function in JavaScript?
- How do I use Lodash with JavaScript?
- How do I use yarn to install and use lodash in a JavaScript project?
- How can I use Lodash's uniq() function to remove duplicate values from a JavaScript array?
- How can I use Lodash to uppercase the first letter of a string in JavaScript?
See more codes...