Reputation: 61
I'm trying to find the cleanest way to implement a filter to an array of objects depending on a string keyword. I need to return those objects whose only specific properties contains the string value.
Let's say I have the following array of objects:
const products = [
{
name: 'car',
price: 100,
image: 'someurl'
email: '[email protected]'
available: true,
},
{
name: 'phone',
price: 200,
image: 'someurl'
email: '[email protected]'
available: false,
},
{
name: 'bottle',
price: 300,
image: 'someurl'
email: '[email protected]'
available: true,
},
];
As mentioned here: Filter array of objects whose any properties contains a value
One of the cleanest way to match any value in an array of objects whose properties have different types would be:
function filterByValue(array, string) {
return array.filter(o =>
Object.keys(o).some(k => String(o[k]).toLowerCase().includes(string.toLowerCase())));
}
This filterByValue function will return those objects whose any properties match the string value.
However, I'd like to add some conditions, so it only iterates and look for some match at "name", "price" and "email" properties, not looking at "image" and "available" properties.
Upvotes: 1
Views: 3138
Reputation: 370699
Make an array of the properties to look at, and look at them instead of using Object.keys
.
const propsToCheck = ['name', 'price', 'email'];
function filterByValue(array, string) {
return array.filter(o =>
propsToCheck.some(k => String(o[k]).toLowerCase().includes(string.toLowerCase())
)
);
}
Upvotes: 3