You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用RxJS合并两个对象?附示例场景

Solution for Combining RxJS Observables as Requested

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:

  1. Split users into Russian and English groups to get the order right (Russian user first, then English users in their original order).
  2. Map each user to the target object structure, pairing their name with the correct month list using their lang property.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:33:24