How to use _.filter() method In Lodash
In this approach, we are using the _.filter() method from lodash to create a new array containing objects from ‘arr‘ where the ‘name‘ property matches ‘w3wiki‘.
Syntax:
_.filter( collection, predicate )
Example: The below example uses the _.filter() method to find and return an object from Array.
const _ = require('lodash');
const arr = [
{
id: 1, name: 'w3wiki',
category: 'Education'
},
{
id: 2, name: 'Stack Overflow',
category: 'Q&A'
},
{
id: 3, name: 'GitHub',
category: 'Development'
}
];
function approach3Fn(arr, key, value) {
return _.filter(arr, [key, value])[0];
}
const res = approach3Fn(arr, 'name',
'w3wiki');
console.log(res);
Output:
{ id: 1, name: 'w3wiki', category: 'Education' }
How to use Lodash to find & Return an Object from Array ?
In JavaScript, the Lodash Module has different methods of doing and get objects from the array. we will explore three different methods with practical implementation of each approach in terms of examples and output to to find and return an object from Array.
These are the following methods:
Table of Content
- Using _.find() method
- Using _.findIndex and _.nth methods
- Using _.filter() method
Contact Us