1

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

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'
  }
] 

两个过滤器可以同时激活,从而过滤两个级别。
例如:部门过滤器选择:“工程”([2] 返回 2 个对象的数组)=> 用户选择第二个过滤器 => 类型过滤器选择:“全职”([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)
    }
  }

提前致谢!

4

3 回答 3

4

仅使用一个.filter, 并在回调中执行检查departmenttype单独的表达式:

jobs.filter((job) => (
  (department === 'all' || job.department === department) &&
  (type === 'all' || job.type === type)
));
于 2021-02-17T20:54:17.043 回答
1
const allFields ='all';
const filteredJobs = jobs.filter(job => 
    (department === allFields || department === job.department) &&
    (type === allFields || type === job.type)
);
于 2021-02-17T21:00:43.227 回答
1

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

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

于 2021-02-17T21:02:46.090 回答