Поскольку вас интересуют вакансии, я бы предложил создать модель 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>