如何创建多过滤功能来过滤掉多个属性? [英] How to create a multi-filter function to filter out multiple attributes?

查看:22
本文介绍了如何创建多过滤功能来过滤掉多个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组要过滤的对象:

<预><代码>[{名称":苹果",年龄":24,型号":Android",状态":开发中",},{名称":机器人",年龄":24,型号":苹果",状态":运行",},....]

我需要使用 JavaScript 的 filter 方法使用多个参数过滤数组.我有一个部分解决方案,但无法获得预期的输出.

过滤器还应该处理单个属性的多个值.例如,age=54,23model=Android"、Apple"

我正在尝试模拟过滤器的工作方式,就像电子商务网站的工作方式一样,我们可以在其中比较产品的所有属性和客户选择的标签,以输出经过过滤的产品列表.

解决方案

如果您像数据数组中的对象一样格式化过滤条件,但值是可能值的数组,那么您可以使用filter方法如下:

let data = [{"name": "苹果",年龄":24,"型号": "安卓","status": "开发中",}, {"name": "机器人",年龄":24,"model": "苹果","状态": "正在运行",}, {"name": "三星",年龄":26,"model": "蓝莓","状态": "正在运行",},];让过滤器 = {"name": ["Roboto", "Ericsson"],年龄":[22, 24, 26],};让 res = data.filter(obj =>Object.entries(filter).every(([prop, find]) => find.includes(obj[prop])));console.log(res);

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",
  },
  
  .
  .
  .
  .

]  

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.

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.

解决方案

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);

这篇关于如何创建多过滤功能来过滤掉多个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆