Javascripot Filter Example; In this tutorial you will learn how to add Filter an Array of Objects based on a property; To use the filter in array object based on property or attributes you can use the Array.filter() or Array.find() methods;
This tutorial show you how to get specific object from array with match id name or single key value
Example 1:
The Array.filter method returns an array with all elements that satisfy the condition.
const users = [
{name: 'Test 1', age: 20},
{name: 'Test 2', age: 30},
{name: 'Test 3', age: 20},
];
const results = users.filter(obj => {
return obj.age === 20;
});
console.log(results); // [{name: 'Test 1', age: 20}, {name: 'Test 3', age: 20}]
if (results.length > 0) {
// the condition was satisfied at least once
}
Example 2:
If you only need to filter for a single object that satisfies a condition in the array, use the Array.find
method.
// Not Supported in IE 6-11
const users = [
{name: 'Test 1', age: 20},
{name: 'Test 2', age: 30},
{name: 'Test 3', age: 20},
];
const person = users.find(object => {
return object.age === 30;
});
console.log(person); // {name: 'Test 2', age: 30}
if (person !== undefined) {
// The condition was satisfied
}