I have an array of objects that have many properties. I would like to be able to find the matching items, based on a filter object that only contains a subset of the arrays properties. For Example, i have a customer
let Customer = {
Name: "John Doe",
Age: 80,
Hair: "Red",
Gender: "Male",
};
And i have my search object:
let searchObject ={
Hair: "Red",
Gender: "Male"
}
I want to be able to find inside my array, all customers that match searchObject, without having to do:
this.array.filter(z=>z.Hair == searchObject.Hair && z.Gender == searchObject.Gender);
I would like for it to be when searchObject adds more properties, it automatically filters on those too
You can use every() on Object.keys() of searchObject inside and check if all the values of keys in searchObject matches with corresponding values of object in array.
Below in the snippet I have two object with different Gender
let array = [{
Name: "John Doe",
Age: 80,
Hair: "Red",
Gender: "Male",
},{
Name: "Marry",
Age: 80,
Hair: "Red",
Gender: "Female",
}]
let searchObject ={
Hair: "Red",
Gender: "Male"
}
const res = array.filter(x => Object.keys(searchObject).every(k => x[k] === searchObject[k]));
console.log(res)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With