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 to remove null values from an object in JavaScript?
- How do I get the last element in an array using Lodash in JavaScript?
- How can I use the Lodash library in JavaScript?
- How can I use Lodash to capitalize a string in JavaScript?
- How do I use the lodash get function in JavaScript?
- How do I use yarn to install and use lodash in a JavaScript project?
- How do I use Lodash in a JavaScript playground?
- How can I use Lodash's xor function to manipulate JavaScript objects?
- How do I use an online JavaScript compiler with Lodash?
- How do I use Lodash to truncate a string in JavaScript?
See more codes...