如何使用RxJS左连接两个基于公共id的json数组

bogh5gae  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(108)

需要关于Rxjs连接的问题的帮助。我有两个带有公共id的观察对象,我想执行连接来显示基于id的两个对象的记录。

let emp = of([
      { id: 1, name: 'aa', age: 20 },
      { id: 2, name: 'bb', age: 21 },
      { id: 3, name: 'cc', age: 22 },
      { id: 4, name: 'dd', age: 23 }
    ]);
   let details = of([
      { id: 1, address: 'ee' },
      { id: 1, address: 'ff' },
      { id: 2, address: 'gg' },
      { id: 2, address: 'hh' }
    ]);

我需要这样的连接:

[
 {id: 1, name: 'aa', age: 20, details: [{address: 'ee'},{address: 'ff'}] },
 {id: 2, name: 'bb', age: 21, details: [{address: 'gg'},{address: 'hh'}] },
 {id: 3, name: 'cc', age: 22, details: undefined },
 {id: 4, name: 'dd', age: 23, details: undefined },
]

我曾这样尝试过:

forkJoin([emp, details]).pipe(
      map(([_emp, _details]) =>
        _emp.map((item) => {
          return ( {
            ...item,
            details: _details.find((item1) => {
              return item1.id === item.id
            })
          })
        })
      )
    ).subscribe(console.log)

我得到了结果:

[
 {id: 1, name: 'aa', age: 20, details: [{address: 'ee'}] }, // {address: 'ff'} missing
 {id: 2, name: 'bb', age: 21, details: [{address: 'gg'}] }, // {address: 'hh'} missing
 {id: 3, name: 'cc', age: 22, details: undefined },
 {id: 4, name: 'dd', age: 23, details: undefined },
]

在此结果中,ID 1和2缺少第二个地址。
而不是[{地址:'ee'},{地址:'ff'}],我只找到了第一个匹配项[{address:'ee'}]表示标识1。
而不是[{地址:'gg'},{地址:'hh'}],我只找到了第一个匹配项[{address:'gg'}]表示标识2。
请帮助我完成预期的结果

sr4lhrrt

sr4lhrrt1#

我认为应该使用filter()而不是find()find()操作符只返回第一个匹配项。

forkJoin([emp, details]).pipe(
      map(([_emp, _details]) =>
        _emp.map((item) => {
          return ({
            ...item,
            // This is the line you have to modify:
            details: _details.filter((item1) => item1.id === item.id)
          })
        })
      )
    ).subscribe(console.log)

相关问题