How to create a multi-filter function to filter out multiple attributes?(如何创建一个多重过滤功能来过滤掉多个属性?)
问题描述
我有一个要过滤的对象数组:
I have an array of objects to be filtered:
[
{
"name": "Apple",
"age": 24,
"model": "Android",
"status": "Under development",
},
{
"name": "Roboto",
"age": 24,
"model": "Apple",
"status": "Running",
},
.
.
.
.
]
我需要使用 JavaScript 的 filter
方法使用多个参数过滤数组.我得到了部分解决方案,但无法获得预期的输出.
I need to filter the array using multiple parameters using JavaScript's filter
method.
I have got a partial solution but could not get the expected output.
过滤器还应该适用于单个属性的多个值.例如,age=54,23
或 model=Android"、Apple"
等.
The filter should also work with multiple values for a single attribute.
E.g., age=54,23
or model="Android","Apple"
etc.
我试图模仿电子商务网站的过滤器的工作方式,我们可以在其中比较产品的所有属性和客户选择的标签,以输出过滤后的产品列表.
I'm trying to mimic the working of filters just like that of an 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.
推荐答案
如果您像数据数组中的对象一样格式化过滤条件,但值是可能值的数组,那么您可以使用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);
这篇关于如何创建一个多重过滤功能来过滤掉多个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何创建一个多重过滤功能来过滤掉多个属性?
基础教程推荐
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01