我正在尝试使用“过滤器”对象过滤一组对象。下面的“过滤器”对象应该过滤数组的对象类型:“玩具”或“电子”,语言:“英语”或“西班牙语”。我正在尝试创建一个函数,该函数将name: 'StoreF'基于提供的过滤器返回最后一个对象 ( ) 作为示例。
var filters = {
country: ["France"],
type: ["toys", "electronics"],
language: ["English", "Spanish"]
}
var stores = [{
name: "StoreA",
country: "United States",
type: ["toys", "groceries"],
language: ["English", "Spanish"]
},
{
name: "StoreB",
country: "Spain",
type: ["toys"],
language: ["English", "Spanish"]
},
{
name: "StoreC",
country: "France",
type: ["autoparts"],
language: ["French"]
},
{
name: "StoreD",
country: "Thailand",
type: ["toys"],
language: ["Thai"]
},
{
name: "StoreE",
country: "India",
type: ["toys"],
language: ["English"]
},
{
name: "StoreF",
country: "France",
type: ["toys"],
language: ["English", "French"]
},
]
使用此函数可以正常工作,直到我为同一类别引入 2 个过滤器(即language: ["English", "Spanish"])。
function nestedFilter(targetArray, filters) {
var filterKeys = Object.keys(filters);
return targetArray.filter(function(eachObj) {
return filterKeys.every(function(eachKey) {
if (!filters[eachKey].length) {
return true;
}
if (!$.isEmptyObject(eachObj[eachKey])) {
return eachObj[eachKey].includes(filters[eachKey]);
}
});
});
};
nestedFilter(stores, filters);
我究竟做错了什么?
慕雪6442864
相关分类