Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
901 views
in Technique[技术] by (71.8m points)

rxjs - Merge subarrays using Observables

I have this data structure:

[{
    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"
        }
    ]
}]

I make the following call to a web service to get the items: this.dataService.get("items")

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"
}]

Should I use something like flatMap or concat?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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));

or in your case

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...