首页 > 解决方案 > 过滤具有可观察条件的观察数组

问题描述

我有一个请求,它返回一个对象数组。每个对象都包含一个 id,我用它发送另一个请求。基于这个结果,我想过滤数组。简化示例:

function getAllObjects(): Observable<{ id: number }[]> {
  return of([
    { id: 1 },
    { id: 2 },
    { id: 3 },
    { id: 4 },
  ]);
}

function checkObject(obj): Observable<boolean> {
  return of(obj.id % 2 === 0);
}

getAllObjects().pipe(
  // TODO
).subscribe(console.log); // I only want to see objects here which passed the async check

标签: javascriptangulartypescriptrxjs

解决方案


那对你有用吗?

getAllObjects().pipe(
  flatMap((ar) => ar),
  concatMap((obj) => combineLatest([of(obj), checkObject(obj)])),
  filter(([_, checkResult]) => checkResult),
  map(([obj]) => obj),
  toArray(),
).subscribe(console.log);

编辑,我看到你已经找到了一个解决方案,我的并不简单,而且我认为你想要一个对象流而不是将它们作为数组返回。所以我在我的编辑中添加了 toArray。


推荐阅读