我正在尝试使用多个不同类型的过滤器( bool 值、字符串匹配等)来过滤网格。网格只是一个 JSON 数组。每次设置或删除过滤器值(即选中或取消选中复选框)时,我都必须进行过滤。我试图使用非常复杂的 switch 语句来做到这一点,但后来我发现 this post作者@ori-drori 解释了如何使用更简单的filterHandlers 映射来做到这一点。然而,当我运行这段代码时,我没有得到想要的结果,我很困惑为什么。这是我得到的:
filterGrid(rows) {
const filterList = [
{ 'open': this.onlyOpen },
{ 'assmtComplete': this.onlyAssmtCompleted },
{ 'bureau': this.selectedBureau ? this.selectedBureau : '' },
{ 'unit': this.selectedUnit ? this.selectedUnit : '' }
];
const filterHandlers = new Map([
[
'open',
(ref) => !ref.cwsClosureReasonDescription
],
[
'assmtComplete',
(ref) => ref.safetyAsstComplDate !== null
],
[
'bureau',
(ref, val) => ref.bureauCode === val
],
[
'unit',
(ref, val) => ref.unitID === val
],
]);
const applyFilters = (arr, filters) => {
const filterKeys = Object.keys(filters);
return arr.filter(o => filterKeys.every((key) => {
const handler = filterHandlers.get(key); // THIS returns undefined every time
return !handler || handler(o[key], filters[key]);
}));
};
const result = applyFilters(rows, filterList);
console.log(result);
}
“行”中的示例对象可能如下所示:
{
createdDate: "2019-10-18T10:56:43.477"
closureReasonDescription: null
refNumber: "1231-3213-2132-1321321"
incidentZipCode: "92108"
intakeDate: "2019-10-19T00:56:24.953"
referralId: 1461
bureauCode: "S"
unitID: 1017
safetyAsstComplDate: null
taskTypeId: null
}
从上面代码的注释中可以看出,applyFilters 中的那一行始终是未定义的。我尝试了几种从中获取处理程序的方法,但我不确定应该使用什么键 - 整数还是字符串?任何提示将不胜感激!
最佳答案
filterKeys
(由 Object.keys(filterList)
定义)是一个数字键数组 (["0", "1", "2", "3"]
),因为 filterList
是一个数组,其键是数字索引。
我认为您希望 filterKeys
成为 filterList
数组中每个对象的键。通过将 filterList
设为具有多个键的单个对象,而不是每个具有一个键的对象数组,可以最轻松地实现这一点:
const filterList = {
'open': this.onlyOpen,
'assmtComplete': this.onlyAssmtCompleted,
'bureau': this.selectedBureau ? this.selectedBureau : '',
'unit': this.selectedUnit ? this.selectedUnit : ''
];
关于Javascript:根据多个值过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58491730/