javascript - 过滤具有可观察条件的观察数组
问题描述
我有一个请求,它返回一个对象数组。每个对象都包含一个 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
解决方案
那对你有用吗?
getAllObjects().pipe(
flatMap((ar) => ar),
concatMap((obj) => combineLatest([of(obj), checkObject(obj)])),
filter(([_, checkResult]) => checkResult),
map(([obj]) => obj),
toArray(),
).subscribe(console.log);
编辑,我看到你已经找到了一个解决方案,我的并不简单,而且我认为你想要一个对象流而不是将它们作为数组返回。所以我在我的编辑中添加了 toArray。
推荐阅读
- javascript - 为什么悬停选择器在跨度中不起作用?
- javascript - JavaScript:如何将正则表达式改为accept(),-.;[]
- java - MavenReportException:未正确设置 JAVA_HOME
- android - 创建卡片时如何在 recyclerview (cardview) 中添加日期。(卡片创建日期)
- python - 安装 python 模块的问题
- python - python列表中的元素可以重新分配其值吗?
- c# - 在 C# 中使用 WooCommerce.NET / Rest API 更新产品属性
- mysql - 连接两个表并在单个查询中返回数据和计数
- python - 将文本列的行拆分为多行
- java - 使用适用于 S3 下载的 AWS 开发工具包时出现 ConnectionPoolTimeOutException