【问题标题】:Filter content based on two dropdown values根据两个下拉值过滤内容
【发布时间】:2021-02-18 05:21:49
【问题描述】:

我有两个下拉菜单,它们用作职位发布的过滤器。

const type = ['all', 'fulltime', 'parttime'];
const department = ['all', 'engineering', 'design'];

这是我要过滤的数据(默认情况下,两个下拉列表的值都是 all

let jobs = [
  { 
    role: 'a',
    department: 'engineering',
    type: 'fulltime'
  },
  { 
    role: 'b',
    department: 'design',
    type: 'parttime'
  },
  { 
    role: 'c',
    department: 'engineering',
    type: 'parttime'
  }
] 

两个过滤器可以同时激活,从而过滤两个级别。
例如:部门过滤器选择:'Engineering'([2] 返回 2 个对象的数组)=> 用户选择第二个过滤器 => 类型过滤器选择:'fulltime'([1] 返回 1 个对象的数组)

所有点击过滤器的all,它应该只重置那个特定的过滤器。

这是我尝试过的,似乎无法找到一个合理的解决方案。

const filterJobs = () => {
    const { department, type} = filters; //filters selected by user

    if(department === 'all'){
      return;
    } else{
      filteredJobs = jobs.filter((job)=>job.department === department)
    }

    if(type === 'all'){
      return;
    } else{
      filteredJobs = jobs.filter((job)=>job.type === type)
    }
  }

提前致谢!

【问题讨论】:

    标签: javascript


    【解决方案1】:

    只使用一个.filter,并在回调中,在单独的表达式中同时检查departmenttype

    jobs.filter((job) => (
      (department === 'all' || job.department === department) &&
      (type === 'all' || job.type === type)
    ));
    

    【讨论】:

      【解决方案2】:

      你可以在一个循环中完成:

      const jobs = [
        { role: 'a', department: 'engineering', type: 'fulltime' },
        { role: 'b', department: 'design', type: 'parttime' },
        { role: 'c', department: 'engineering', type: 'parttime' }
      ];
      
      const filterJobs = (filters) => {
        let { department='all', type='all' } = filters;
        return jobs.filter(job => 
          (department==='all' || job.department === department) &&
          (type==='all' || job.type === type)
        );
      }
      
      console.log( filterJobs({ department: 'all', type: 'fulltime' }) );
      console.log( filterJobs({ department: 'all', type: 'parttime' }) );
      console.log( filterJobs({ department: 'engineering', type: 'parttime' }) );

      【讨论】:

        【解决方案3】:
        const allFields ='all';
        const filteredJobs = jobs.filter(job => 
            (department === allFields || department === job.department) &&
            (type === allFields || type === job.type)
        );
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-21
          • 1970-01-01
          • 2020-10-15
          • 1970-01-01
          • 2021-10-17
          • 2018-04-16
          • 1970-01-01
          相关资源
          最近更新 更多