Angular中RxJS实现嵌套对象Workheads.Code深层过滤的方法咨询
RxJS 嵌套字段过滤实现方案
前置准备:定义 TypeScript 类型
先给接口数据定义类型,方便后续类型校验:
// 嵌套的Workheads字段类型 interface Workhead { ID: string; Name: string; Code: string; } // 外层返回对象类型 interface Company { ID: string; UEN: string; Name: string; Address: string; Telephone: string; Fax: string; Email: string; Website: string; Postal: string; Status: any; // 可替换为实际返回的枚举/数值类型 TimeCreated: any; TimeUpdated: any; Workheads: Workhead[]; }
基础场景:固定匹配值过滤
如果你只需要根据指定的固定值做一次过滤,直接在HTTP请求的Observable管道中使用map操作符处理返回的数组即可:
import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs'; // 目标匹配码,可替换为用户输入的变量 const targetCode = 'CS2230'; this.http.get<Company[]>('你的API请求地址').pipe( // 对Observable返回的整个企业数组做筛选 map(companyList => companyList.filter(company => // 判断当前企业下的Workheads是否存在至少一个Code匹配的项 company.Workheads.some(workhead => workhead.Code === targetCode) ) ) ).subscribe(filteredList => { // filteredList就是筛选后的外层对象数组 console.log('匹配结果:', filteredList); });
进阶场景:响应用户输入实时过滤
如果需要根据用户输入的内容动态筛选,可结合表单控件的valueChanges事件实现:
import { FormControl } from '@angular/forms'; import { combineLatest, startWith, switchMap } from 'rxjs'; // 绑定用户输入框的表单控件 searchControl = new FormControl(''); // 方案A:每次输入都重新请求接口(适合数据量大的场景) this.searchControl.valueChanges.pipe( startWith(''), // 初始加载时默认空字符串匹配所有 switchMap(keyword => this.http.get<Company[]>('你的API请求地址').pipe( map(companyList => { const trimKeyword = keyword.trim(); // 这里用includes实现模糊匹配,需要完全匹配可替换为=== return companyList.filter(company => company.Workheads.some(wh => wh.Code.includes(trimKeyword)) ) }) ) ) ).subscribe(filteredList => console.log('实时匹配结果:', filteredList)); // 方案B:仅请求一次全量数据,本地过滤(适合数据量小的场景,性能更高) const allCompany$ = this.http.get<Company[]>('你的API请求地址'); combineLatest([ allCompany$, this.searchControl.valueChanges.pipe(startWith('')) ]).pipe( map(([companyList, keyword]) => { // 可选:大小写不敏感匹配 const formatKeyword = keyword.trim().toLowerCase(); return companyList.filter(company => company.Workheads.some(wh => wh.Code.toLowerCase().includes(formatKeyword)) ) }) ).subscribe(filteredList => console.log('实时匹配结果:', filteredList));
注意事项
- 如果接口可能返回空的
Workheads字段,可添加可选链避免报错:company.Workheads?.some(...) ?? false - 完全匹配使用
===运算符,模糊匹配使用includes运算符,可根据业务需求调整 - 不需要大小写敏感的场景,统一将匹配值和Code转成小写/大写再做对比
内容的提问来源于stack exchange,提问作者Kim
相关产品推荐
相关产品推荐

