使用 Observables 合并子数组 [英] Merge subarrays using Observables
问题描述
我有这个数据结构:
[{
id : 1,
name : "Item 1",
subItems : [{
id : 1,
name : "SubItem 1"
},{
id : 2,
name : "SubItem 2"
}
]
}, {
id : 2,
name : "Item 2",
subItems : [{
id : 3,
name : "SubItem 3"
}, {
id : 4,
name : "SubItem 4"
}
]
}]
我对网络服务进行以下调用以获取项目:this.dataService.get("items")
I make the following call to a web service to get the items:
this.dataService.get("items")
返回的是一个 Observable
.我可以使用哪些 Observable 运算符来仅获取子项的串联列表?我想以这样的方式结束:
Returned is an Observable<Item[]>
. What Observable operators can I use to only get a concatenated list of SubItems? I would like to end up with something like this:
[{
id : 1,
name : "SubItem 1"
}, {
id : 2,
name : "SubItem 2"
},
{
id : 3,
name : "SubItem 3"
}, {
id : 4,
name : "SubItem 4"
}]
我应该使用 flatMap
或 concat
之类的东西吗?
Should I use something like flatMap
or concat
?
推荐答案
假设它是一个错字并且第二个元素也有 subItems
(而不是 searchProfiles
),您不需要 flatMap 或任何类似的东西,您可以使用 js 数组运算符在普通地图中完成它:
Provided it is a typo and the second element has subItems
as well (and not searchProfiles
), you don't need flatMap or any thing of the sort, you can do it in a plain map using js array operators:
var transformed = [].concat(...result.map(item => item.subItems));
或者你的情况
httpResult$.map(result => [].concat(...result.map(item => item.subItems))
如果故意使用不同的键,您的内部映射将需要更多的逻辑,但映射将完全相同
if the use of different keys is deliberate, your internal map will require a bit more logic but the mapping will be quite the same
这篇关于使用 Observables 合并子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!