Javascript:根据多个值过滤对象数组
我正在尝试使用多种类型的过滤器(布尔、字符串匹配等)过滤网格。网格只是一个JSON数组。每次设置或删除筛选值(即选中或取消选中复选框)时,我都必须进行筛选。我试图使用一个非常复杂的switch语句来实现这一点,但后来我发现@ori drori解释了如何使用一个更简单的过滤器句柄映射来实现这一点。然而,当我运行这段代码时,我没有得到想要的结果,我很困惑为什么。以下是我得到的:Javascript:根据多个值过滤对象数组,javascript,arrays,typescript,filter,Javascript,Arrays,Typescript,Filter,我正在尝试使用多种类型的过滤器(布尔、字符串匹配等)过滤网格。网格只是一个JSON数组。每次设置或删除筛选值(即选中或取消选中复选框)时,我都必须进行筛选。我试图使用一个非常复杂的switch语句来实现这一点,但后来我发现@ori drori解释了如何使用一个更简单的过滤器句柄映射来实现这一点。然而,当我运行这段代码时,我没有得到想要的结果,我很困惑为什么。以下是我得到的: filterGrid(rows) { const filterList = [ { 'open': thi
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
}
从上面代码中的注释可以看出,applyFilter中的那一行始终未定义。我尝试了几种方法从中获取处理程序,但我不确定键应该是什么-整数还是字符串?任何提示都将不胜感激 filterKeys
(由对象定义。键(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 : ''
];
键是对象中某个属性的名称,因此在您的示例中是“createdDate”。对,这就是我的想法,但行“const filterKeys=object.keys(filters);”返回一个字符串数组,它实际上只是每个过滤器的索引(即[0”、“1”、“2”、“3”)。但它应该返回这个:[“打开”、“关联完成”、“局”、“单位”],对吗?那我怎么才能拿到正确的钥匙呢?感谢Object.keys的使用,filterList的定义如下:{open:this.onlyOpen,assmtComplete:this.onlyasmtcompleted,etc.};是的,你说得对,它应该是一个带键的对象。我做了那个改变,现在它抓取了正确的过滤器来比较每条记录。非常感谢。