如何创建一个使用JS过滤掉多个属性的多重过滤器功能? [英] How to create a multi-filter function to filter out multiple attributes using JS?
问题描述
[
{
"name": "Apple",
"age": 24,
"model": "Android",
"status": "Under development",
},
{
"name": "Roboto",
"age": 24,
"model": "Apple",
"status": "Running",
},
.
.
.
.
]
我需要使用JS筛选器方法使用多个参数来筛选数组. 我有一个局部解决方案,无法获得预期的输出(卡在上面).
I need to filter the array using multiple parameters using JS filter method. I have got a partial solution and could not get the expected output (stuck on it).
在这里,过滤器还应该为单个属性使用多个值. 例如,age = 54,23或model = Android,Apple等.
Here, the filter should also work with multiple values for a single attribute. Eg., age=54,23 or model=Android,Apple etc.
简单地说,我正在尝试模仿过滤器的工作方式 电子商务网站上,我们可以在其中比较产品的所有属性和客户选择的标签,以输出过滤后的产品列表.
Simply said, I'm trying to mimic the working of filters just like that of a e-commerce site where we can compare all of a product’s attributes and customer’s chosen tags to output a filtered list of products.
任何帮助都是有意义的. 谢谢!
Any help is appreciable. Thanks!
推荐答案
如果您将过滤条件设置为与数据数组中的对象一样的格式,但其值是可能值为 arrays 的数组,那么您可以使用filter
方法,如下所示:
If you format your filter conditions just like an object in your data array, but with values being arrays of possible values, then you can use the filter
method as follows:
let data = [
{
"name": "Apple",
"age": 24,
"model": "Android",
"status": "Under development",
}, {
"name": "Roboto",
"age": 24,
"model": "Apple",
"status": "Running",
}, {
"name": "Samsung",
"age": 26,
"model": "Blueberry",
"status": "Running",
},
];
let filter = {
"name": ["Roboto", "Ericsson"],
"age": [22, 24, 26],
};
let res = data.filter(obj =>
Object.entries(filter).every(([prop, find]) => find.includes(obj[prop])));
console.log(res);
这篇关于如何创建一个使用JS过滤掉多个属性的多重过滤器功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!