使用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<Item[]>
.我可以使用哪些可观察到的运算符来仅获取子项的串联列表?我想结束这样的事情:
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屋!