Javascript/Typescript/Lodash/Angular多选下拉实现对象列表过滤问题
解决方案
核心问题说明
你当前代码的问题主要有2处:
- 循环处理选中项时,每遍历一个选中值就重写一次
activeFilters对应字段的校验规则,还重复调用filter(),存在无效逻辑 - 校验规则写反:你用
val.includes(x)是模糊匹配,比如选中"York"也会命中"New York"的条目,实际你需要的是精确匹配「当前条目的字段值是否在选中的多选项数组中」
实现代码
1. 首先实现通用筛选方法,后续新增字段无需重复写逻辑
// 通用筛选设置方法,传入字段名即可复用 setFilter(fieldName) { const selectedOptions = this.filtersData.get(fieldName).value; const selectedValues = selectedOptions.map(opt => opt.itemName); // 只要选了All或者没有选中项,就移除对应字段的筛选规则 if (selectedValues.includes('All') || selectedValues.length === 0) { this.removeFilter(fieldName); this.filter(); return; } // 精确匹配规则:当前条目的字段值在选中值数组内即命中 this.activeFilters[fieldName] = (fieldValue) => selectedValues.includes(fieldValue); this.filter(); }
原来的filterLocation、filterCategory方法可以直接简化为调用通用方法:
- location筛选:
this.setFilter('location') - category筛选:
this.setFilter('category') - 后续新增筛选字段,直接新增一行调用
this.setFilter('新增字段名')即可,扩展性拉满
2. 优化核心过滤逻辑,把status判断提前减少无效遍历
filter() { this.filteredData = _.filter(this.getListings, item => { // 先过滤有效状态,再匹配所有筛选规则 return item.status === true && _.conforms(this.activeFilters)(item); }); }
3. 确保removeFilter方法逻辑正确
removeFilter(fieldName) { if (this.activeFilters.hasOwnProperty(fieldName)) { delete this.activeFilters[fieldName]; } }
效果验证
同时选中location的New York和Miami、category的Food时,activeFilters会自动生成2条匹配规则,最终返回符合所有条件的data1和data3,完全符合多选+多字段组合筛选的需求。
内容的提问来源于stack exchange,提问作者Novakinify
相关产品推荐
相关产品推荐

