RXJS单次发射时从父级可观察数组提取嵌套schedule数组的方法
RxJS提取合并Collection中Schedule数组实现方案
场景说明
你的需求是对Observable发射的Collection数组,提取每个元素下的schedule子数组,最终合并为一个一维的Schedules数组。你之前尝试的forkJoin、combineLatest属于多Observable组合操作符,不适用于单Observable发射数据的结构转换场景,直接使用基础操作符即可实现。
实现方案
1. 纯同步结构转换(无额外异步逻辑)
如果你的源Observable是单次发射完整的Collection数组(比如HTTP接口返回结果),直接用map配合数组原生flatMap方法即可:
import { map, of } from 'rxjs'; // 模拟源Observable,替换为你自己的数据源 const mockCollections = [ { id: 'col1', purpose: '测试1', balance: '100', creator: 'user1', dateCreated: '2024-01-01', dateUpdated: '2024-01-01', userId: 'u1', schedule: [ {id: 's1', amount: '10', status: '待处理', type: '收入', dateCreated: '2024-01-02', dateUpdated: '2024-01-02'}, {id: 's2', amount: '20', status: '已完成', type: '支出', dateCreated: '2024-01-03', dateUpdated: '2024-01-03'} ] }, { id: 'col2', purpose: '测试2', balance: '200', creator: 'user2', dateCreated: '2024-01-04', dateUpdated: '2024-01-04', userId: 'u2', schedule: [ {id: 's3', amount: '30', status: '待处理', type: '收入', dateCreated: '2024-01-05', dateUpdated: '2024-01-05'}, {id: 's4', amount: '40', status: '已完成', type: '支出', dateCreated: '2024-01-06', dateUpdated: '2024-01-06'} ] } ]; const collections$ = of(mockCollections); // 转换逻辑 const allSchedules$ = collections$.pipe( map(collections => collections.flatMap(collection => collection.schedule)) ); // 订阅获取结果 allSchedules$.subscribe(schedules => { console.log(schedules); // 输出[s1, s2, s3, s4]组成的一维数组 });
如果运行环境不支持Array.prototype.flatMap,可以替换为map(collections => collections.map(c => c.schedule).flat()),效果完全一致。
2. 含异步处理场景(需要对单个Schedule做额外操作)
如果你需要对提取出的每个Schedule做异步处理(比如调用接口查询详情),可以搭配mergeMap、from、toArray实现:
import { map, mergeMap, from, toArray } from 'rxjs'; const allSchedules$ = collections$.pipe( // 先提取所有schedule合并为一维数组 map(collections => collections.flatMap(c => c.schedule)), // 将数组转为逐个发射schedule项的Observable mergeMap(schedules => from(schedules)), // 对单个schedule做异步处理,示例为调用查询详情接口,替换为你自己的异步逻辑 mergeMap(schedule => getScheduleDetailApi(schedule.id)), // 所有异步处理完成后合并为数组 toArray() );
内容的提问来源于stack exchange,提问作者Kim
相关产品推荐
相关产品推荐

