【发布时间】:2020-12-23 18:25:49
【问题描述】:
我有一个动态的过程 - 根据复选框状态的变化 - 创建一种 config 对象,该对象描述了应该如何构建过滤数据项数组的条件。 p>
过滤器配置可能如下所示...
const filter = {
publicationType: ['type-1', 'type-2'],
termType: ['term-1', 'term-2'],
reportFormat: ['xml'],
}
数据项的简化列表如下所示...
const data = [
{ id: 1, reportFormat: 'txt', termType: 'term-1', publicationType: 'type-1' },
{ id: 2, reportFormat: 'xml', termType: 'term-2', publicationType: 'type-2' },
{ id: 3, reportFormat: 'txt', termType: 'term-2', publicationType: 'type-2' },
]
我希望条件匹配每个类别/类型(配置的键),但它的值可以是类别/类型数组中的任一个。 p>
根据提供的示例数据和规范,预期的过滤结果将是......
[{ id: 2, reportFormat: 'xml', termType: 'term-2', publicationType: 'type-2' }]
一种基于提供的filter 配置对象构建正确过滤条件的方法看起来如何。
下面是我尝试制作过滤器功能,但如果我尝试过滤多个 Select 组件 - 数据重复,过滤只能在单个 Select 组件上正常工作。
const handleFilter = (val) => {
const filterKeys = Object.keys(val);
const filteredStats = [];
// loop objects in fetched arr
for (const item of stat) {
// loop properties by which filtering data
filterKeys.forEach((keys) => {
// check if data property match with a filtering property in array
const isPresent = val[keys].some((key) => {
const statProperty = item[keys];
const filterProperty = key;
return filterProperty === statProperty;
});
if (isPresent) {
filteredStats.push(item);
}
});
}
setfilteredState(filteredStats);
};
https://codesandbox.io/s/checkbox-filter-vqex7?file=/src/App.js
【问题讨论】:
-
指定 "by all properties together" ...这是否意味着一个大的
AND链接条件,如publicationType === 'type-1' && publicationType === 'type-2' && termType === 'term-1' && termType === 'term-2' ...?...因为这不起作用或者是每个类别/类型都匹配其值中的任何一个? -
reportFormat: 'txt'来自哪里? -
我添加了我的代码和沙箱,例如@evolutionxbox
标签: javascript arrays data-structures dynamic filter