Hi team I have an array of objects like
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" }
];
Here i need to filter the data
array based on the filter condition
{
"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"
}
I can do this simply using process()
in Kendo
like
kendo.data.Query.process(data, {
filter: {
logic: "and",
filters: [{
field: "subcategory",
value: "Meat",
operator: "eq"
}],logic:"or"
}
});
So is there any other way to filter like this without using process()
?
This approach takes a filters
object which contains an array and a logic part as quantifier for the conditions.
The array can contain other objects with filters
quantifier as logic
or an object with the constraints for a single property which have to match an item of the given data array.
Actually only one operator is implemented.
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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.