我有一个具有许多属性的对象数组。我希望能够基于仅包含数组属性子集的过滤器对象找到匹配项。例如,我有一个客户
let Customer = {
Name: "John Doe",
Age: 80,
Hair: "Red",
Gender: "Male",
};
我有我的搜索对象:
let searchObject ={
Hair: "Red",
Gender: "Male"
}
我希望能够在数组中找到所有与searchObject匹配的客户,而不必这样做:
this.array.filter(z=>z.Hair == searchObject.Hair && z.Gender == searchObject.Gender);
我希望当searchObject添加更多属性时,它也会自动对这些属性进行过滤
最佳答案
您可以在内部的every()
的Object.keys()
上使用searchObject
,并检查searchObject
中的键的所有值是否与数组中对象的相应值匹配。
下面的代码段中,我有两个对象的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)