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 can I compare the usage of lodash's foreach to the native JavaScript foreach loop?
- How do lodash and underscore differ in JavaScript?
- How can I use Lodash's xor function to manipulate JavaScript objects?
- How can I use Lodash to create a unique array in JavaScript?
- How can I check for undefined values in JavaScript using Lodash?
- How can I use Lodash to manipulate JavaScript objects online?
- How do I use Lodash in a JavaScript playground?
- How do I use an online JavaScript compiler with Lodash?
- How can I remove a value from an array using JavaScript and Lodash?
- How can I use Lodash to find and update an object in a JavaScript array?
See more codes...