Angular 10 单个输入框多字段搜索实现Material数据表格过滤效果问题
问题核心原因
- 错误使用对象展开语法
{...arr1, ...arr2}合并数组:该操作会将数组转换为以索引为key的普通对象,返回值不符合IPatient[]的类型要求,同时会覆盖相同索引位置的数组元素,导致结果丢失数据 - 合并过滤结果时遗漏了lastName的匹配结果
- 未对多条件匹配的重复结果去重,会出现同一条数据多次返回的问题
最优实现方案
直接在单次filter遍历中判断所有匹配条件,不需要分开过滤再合并,性能更高也不会出现重复问题:
constructor() { this.filteredPatient = this.patientsearch.valueChanges .pipe( startWith(''), map(p => p ? this._filterPatient(p) : this.patients.slice()) ); } private _filterPatient(value: string): IPatient[] { const filterValue = value.toLowerCase(); // 满足任意一个匹配规则就会被保留 return this.patients.filter(p => p.firstName.toLowerCase().includes(filterValue) || p.lastName.toLowerCase().includes(filterValue) || p.mobileNumber.toLowerCase().includes(filterValue) ); }
扩展场景方案(如需分开处理不同字段的匹配逻辑)
如果后续要扩展不同字段的匹配权重、高亮规则等需求,可以用数组合并+去重的方式实现:
private _filterPatient(value: string): IPatient[] { const filterValue = value.toLowerCase(); const searchByfirstName = this.patients.filter(p => p.firstName.toLowerCase().includes(filterValue)); const searchBylastName = this.patients.filter(p => p.lastName.toLowerCase().includes(filterValue)); const searchBymobileNumber = this.patients.filter(p => p.mobileNumber.toLowerCase().includes(filterValue)); // 数组合并后通过患者唯一id去重 return Array.from(new Map( [...searchByfirstName, ...searchBylastName, ...searchBymobileNumber].map(item => [item.id, item]) ).values()); }
内容的提问来源于stack exchange,提问作者MD SHAFFAT
相关产品推荐
相关产品推荐

