您好,我有很多类似的对象
data = [
{ name: "Pork", category: "Food", subcategory: "Meat" },
{ name: "Pepper", category: "Food", subcategory: "Vegetables" },
{ name: "Beef", category: "Food", subcategory: "Meat" },
{ name: "banana", category: "Food", subcategory: "Fruit" }
];
这里我需要根据过滤条件过滤data
数组
{
"filters":[
{
"filters":[
{
"field":"subcategory",
"operator":"eq",
"value":"Vegetables"
}
],
"logic":"or"
},
{
"filters":[
{
"field":"name",
"operator":"eq",
"value":"Pepper"
},
{
"field":"name",
"operator":"eq",
"value":"banana"
}
],
"logic":"or"
}
],"logic":"and"
}
我可以像在process()
中使用Kendo
一样
kendo.data.Query.process(data, {
filter: {
logic: "and",
filters: [{
field: "subcategory",
value: "Meat",
operator: "eq"
}],logic:"or"
}
});
那么有没有其他方法可以像这样不使用process()
进行过滤?
答案 0 :(得分:1)
此方法采用一个filters
对象,该对象包含一个数组和一个逻辑部分作为条件的量词。
该数组可以包含其他filters
量为logic
的对象,或者一个具有单个属性约束的对象,这些对象必须匹配给定数据数组的项。
实际上只实现了一个运算符。
const
operators = { eq: (a, b) => a === b },
quantifiers = { and: 'every', or: 'some' },
filter = ({ filters, logic }) => item => filters[quantifiers[logic]](f => 'filters' in f
? filter(f)(item)
: operators[f.operator](item[f.field], f.value)
),
filters = { filters: [{ filters: [{ field: "subcategory", operator: "eq", value: "Vegetables" }], logic: "or" }, { filters: [{ field: "name", operator: "eq", value: "Pepper" }, { field: "name", operator: "eq", value: "banana" }], logic: "or" }], logic: "and" },
data = [{ name: "Pork", category: "Food", subcategory: "Meat" }, { name: "Pepper", category: "Food", subcategory: "Vegetables" }, { name: "Beef", category: "Food", subcategory: "Meat" }, { name: "banana", category: "Food", subcategory: "Fruit" }],
result = data.filter(filter(filters));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }