Instead of iterating through an array with a loop to find a specific object, we can simply use a _.find method.
Learn Lodash JS at Lodash JS Tutorial with Examples.
Learn Lodash JS at Lodash JS Tutorial with Examples.
Lodash _.find Method Example
<!DOCTYPE html>
<html>
<head>
<title>Lodash Tutorial</title>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
<script type="text/javascript">
// Lodash first and last array elements
var users = [
{ firstName: "John", lastName: "Doe", age: 28, gender: "male" },
{ firstName: "Jane", lastName: "Doe", age: 5, gender: "female" },
{ firstName: "Jim", lastName: "Carrey", age: 54, gender: "male" },
{ firstName: "Kate", lastName: "Winslet", age: 40, gender: "female" }
];
var user = _.find(users, { lastName: "Doe", gender: "male" });
console.log(user);
// user -> { firstName: "John", lastName: "Doe", age: 28, gender: "male" }
var underAgeUser = _.find(users, function(user) {
return user.age < 18;
});
console.log(underAgeUser);
</script>
</head>
<body></body>
</html>
The above HTML prints below output on the console:
{firstName: "John", lastName: "Doe", age: 28, gender: "male"}
{firstName: "Jane", lastName: "Doe", age: 5, gender: "female"}
Comments
Post a Comment