如何使用RxJS合并两个对象?附示例场景
Got it, let's work through this RxJS problem to get exactly the output you need! Here's how to combine the two Observables and transform the data step by step:
Step-by-Step Explanation
First, we need to get the values from both Observables since we need users and their corresponding month lists. Since both users$ and months$ are cold Observables that emit only once, forkJoin is perfect here—it waits for both Observables to complete and returns their last emitted values as an array.
Next, we'll transform the combined data to match your desired output:
- Split users into Russian and English groups to get the order right (Russian user first, then English users in their original order).
- Map each user to the target object structure, pairing their name with the correct month list using their
langproperty.
Complete Code
import { forkJoin, of } from 'rxjs'; import { map } from 'rxjs/operators'; // Your original Observables const users$ = of([ {id: 1, name: 'Arthur', lang: 'en'}, {id: 2, name: 'Asset', lang: 'ru'}, {id: 3, name: 'Steve', lang: 'en'} ]); const months$ = of({ ru: ['Январь', 'Февраль'], en: ['January', 'February'] }); // Combine and transform the data const result$ = forkJoin([users$, months$]).pipe( map(([users, months]) => { // Separate users by language to match the output order const russianUsers = users.filter(user => user.lang === 'ru'); const englishUsers = users.filter(user => user.lang === 'en'); // Map each user to the required object format return [ ...russianUsers.map(user => ({ months: months[user.lang], user: user.name })), ...englishUsers.map(user => ({ months: months[user.lang], user: user.name })) ]; }) ); // Subscribe to see the result result$.subscribe(output => console.log(output));
Output
When you run this code, you'll get exactly the structure you requested:
[ { months: ['Январь', 'Февраль'], user: 'Asset' }, { months: ['January', 'February'], user: 'Arthur' }, { months: ['January', 'February'], user: 'Steve' } ]
If you wanted to use combineLatest instead of forkJoin, it would work too here—since both Observables only emit once, the behavior is identical. forkJoin is just more semantically correct for single-emission Observables like these.
内容的提问来源于stack exchange,提问作者Abdubek Zholay

