如何使用筛选数组过滤包含数组类型标签字段的对象列表
现有数据结构
待筛选的源数据格式:
results = [ { id: 1, status : "Active", // 其余业务字段 tags : [{val: 'IGM', color: 'light-success' }, {val: 'Gated Out', color: 'light-primary' }, ] }, // 其余数据条目 ]
筛选入参来自多选组件,格式为对象数组:
[{value: 'Gated Out', label: 'GATED OUT'}, ... ]
原有筛选逻辑仅支持字符串类型字段(如status)筛选,无法适配数组类型的tags字段,原有代码如下:
const handleTagsFilter = (value) => { let updatedData = [] const dataToFilter = () => { if ( status.length || custom_tags.length ) { return filteredData } else { return results } } setCustomTags(value) if (value.length) { updatedData = dataToFilter().filter((item) => { const startsWith = item.status.toLowerCase().startsWith(value.toLowerCase()) const includes = item.status.toLowerCase().includes(value.toLowerCase()) if (startsWith) { return startsWith } else if (!startsWith && includes) { return includes } else return null }) setFilteredData([...updatedData]) setCustomTags(value) } }
调整后代码
核心修改点:
- 提前提取多选入参的实际匹配值,统一转小写规避大小写差异问题
- 新增tags数组遍历逻辑,提取每个条目标签的
val值做匹配 - 保留原有字符串字段筛选能力,匹配规则可按需调整为「命中任意标签」或「命中所有标签」
const handleTagsFilter = (selectedTags) => { // 提取选中标签的匹配值,统一转小写 const selectedTagValues = selectedTags.map(tag => tag.value.toLowerCase()) setCustomTags(selectedTags) // 复用原有数据源判断逻辑 const sourceData = status.length || custom_tags.length ? filteredData : results // 未选中标签时直接返回对应数据源 if (!selectedTagValues.length) { setFilteredData([...sourceData]) return } const updatedData = sourceData.filter((item) => { // 原有status字段匹配逻辑,不需要可删除 const statusLower = item.status.toLowerCase() const statusMatch = selectedTagValues.some(keyword => statusLower.startsWith(keyword) || statusLower.includes(keyword) ) // tags数组匹配逻辑 const itemTagValues = item.tags.map(tag => tag.val.toLowerCase()) // 规则:命中任意选中标签即保留,若要求命中所有选中标签,将some替换为every即可 const tagsMatch = selectedTagValues.some(selectedVal => itemTagValues.includes(selectedVal) ) // 两个字段任意一个命中即返回,仅需筛tags时直接返回tagsMatch return statusMatch || tagsMatch }) setFilteredData([...updatedData]) }
注意:如果业务要求筛选时同时匹配status和tags条件,将返回值的
||替换为&&即可。
内容的提问来源于stack exchange,提问作者atropa belladona
相关产品推荐
相关产品推荐

