KnockoutJS按特定属性过滤

时间:2019-01-03 14:35:36

标签: javascript jquery json knockout.js filter

我使用JS中的getJSON方法将KnockoutJS用于求职网站。

不幸的是,我得到了这样的结构:

  • 办公室

    • 纽约

      • 部门
        • 财务
          • 工作
            • 示例
            • ...
        • IT
        • 物流
        • 营销
    • 华盛顿

      • 部门
        • 财务
        • IT
        • 物流
        • 营销
    • 洛杉矶

      • 部门
        • 财务
        • IT
        • 物流
        • 营销

我使用JS中的filter功能过滤掉一些尚未开放的城市办公室,效果很好。

但是现在我需要过滤掉除物流 以外的所有部门,因为我只想显示特定城市的物流工作。我希望它是动态的,因此即使将来有更多部门,它也只会显示后勤

我找不到一个好的解决方案。有什么想法吗?

编辑:这是虚拟JSON:

enter image description here

1 个答案:

答案 0 :(得分:1)

由于您对工作感兴趣,因此建议创建一个Job模型,该模型将当前仅由结构定义的数据合并到一个方便的对象中。

要整理数据,请执行一组reduce操作:

const jobData={offices:[{location:"ny",departments:[{name:"Logistics",jobs:[{title:"driver for x"},{title:"driver for y"}]},{name:"Finance",jobs:[{title:"CFO"}]}]},{location:"la",departments:[{name:"Logistics",jobs:[{title:"driver for z"}]},{name:"IT",jobs:[{title:"tech support manager"}]}]}]}


const Job = (title, department, officeLocation) => ({
  title,
  department,
  officeLocation
});

const JobList = ({ offices }) => ({
  jobs: offices.reduce(
    (allJobs, { location, departments }) => departments.reduce(
      (allJobs, { name, jobs }) => jobs.reduce(
        (allJobs, { title }) => allJobs.concat(
          Job(title, name, location)
        ),
        allJobs
      ),
      allJobs
    ),
    []
  )
})

console.log(JobList(jobData))

现在我们已经整理好数据格式,可以开始编写敲除代码了。

我已经创建了一个table来呈现作业的计算列表。在计算中,我们对2个属性进行过滤:必需的办公室和必需的部门。

过滤器本身是“平坦的”,因为Job对象具有我们所需的所有数据。例如,“物流过滤器”可以按以下方式应用:

const logisticsJobs = ko.pureComputed(
  jobList().filter(job => job.department === "logistics")
);

这里是例子。使用表格标题中的<select>元素来应用过滤器。

function JobFinder() {
  const jobData = ko.observable({ offices: [] });
  const jobList = ko.pureComputed(
    () => JobList(jobData())
  );
  
  // Lists of properties we can filter on
  this.offices = ko.pureComputed(
    () => uniques(jobList().map(job => job.officeLocation))
  );
  
  this.departments = ko.pureComputed(
    () => uniques(jobList().map(job => job.department))
  );
  
  // Filter values
  this.requiredOffice = ko.observable(null);
  this.requiredDepartment = ko.observable(null);
  
  // Actual filter logic
  const officeFilter = ko.pureComputed(
    () => this.requiredOffice()
      ? job => job.officeLocation === this.requiredOffice()
      : () => true
  );
  
  const departmentFilter = ko.pureComputed(
    () => this.requiredDepartment()
      ? job => job.department === this.requiredDepartment()
      : () => true
  );
  
  const allFilters = ko.pureComputed(
    () => [ officeFilter(), departmentFilter() ]
  )
  
  const filterFn = ko.pureComputed(
    () => job => allFilters().every(f => f(job))
  )
  
  // The resulting list
  this.filteredJobs = ko.pureComputed(
    () => jobList().filter(filterFn())
  );

  // To load the data (can be async in real app)
  this.loadJobData = function() {
    jobData(getJobData());
  }
};

// Initialize app
const app = new JobFinder();
ko.applyBindings(app);
app.loadJobData();


// utils
function uniques(xs) { return Array.from(new Set(xs)); }


// Code writen in the previous snippet:
function getJobData() { 
  return {offices:[{location:"ny",departments:[{name:"Logistics",jobs:[{title:"driver for x"},{title:"driver for y"}]},{name:"Finance",jobs:[{title:"CFO"}]}]},{location:"la",departments:[{name:"Logistics",jobs:[{title:"driver for z"}]},{name:"IT",jobs:[{title:"tech support manager"}]}]}]};
};


function Job(title, department, officeLocation) {
  return {
    title,
    department,
    officeLocation
  }
};

function JobList({ offices }) {
  return offices.reduce(
    (allJobs, { location, departments }) => departments.reduce(
      (allJobs, { name, jobs }) => jobs.reduce(
        (allJobs, { title }) => allJobs.concat(
          Job(title, name, location)
        ),
        allJobs
      ),
      allJobs
    ),
    []
  )
};
th { 
  text-align: left;
  width: 30% 
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<table>
  <thead>
    <tr>
      <th>Job Title</th>
      <th>Location</th>
      <th>Department</th>
    </tr>
    <tr>
      <th></th>
      <th>
        <select data-bind="
          options: offices,
          value: requiredOffice,
          optionsCaption: 'Show all locations'">
        </select>
      </th>
        <th>
        <select data-bind="
          options: departments,
          value: requiredDepartment,
          optionsCaption: 'Show all departments'">
        </select>
      </th>
    </tr>
  </thead>
  <tbody data-bind="foreach: filteredJobs">
    <tr>
      <td data-bind="text: title"></td>
      <td data-bind="text: officeLocation"></td>
      <td data-bind="text: department"></td>
    </tr>
  </tbody>
</table>