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 calledusersconst user = _.find(users, { 'age': 36 });- uses Lodash's_.findmethod to find an object with anageproperty set to 36console.log(user);- prints the found object to the console
Helpful links
- Lodash documentation: https://lodash.com/docs/4.17.15
_.findmethod documentation: https://lodash.com/docs/4.17.15#find
More of Javascript Lodash
- 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 to create a unique array in JavaScript?
- How do I use Lodash to truncate a string in JavaScript?
- How do I use Lodash to get unique values in a JavaScript array?
- How can I use Lodash to capitalize a string in JavaScript?
- How can I use Lodash in a JavaScript REPL?
- How can I compare the usage of lodash's foreach to the native JavaScript foreach loop?
- How can I use lodash in a JavaScript sandbox?
- How can I remove a value from an array using JavaScript and Lodash?
See more codes...