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 web service call to get the elements:   this.dataService.get("items")

Returned Observable<Item[]>. What Observable operators can I use to get only a concatenated list of SubItems? I would like to get 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 flatMapor concat?

0
source share
2 answers

Provided that it is a typo, and the second element has subItems(but not searchProfiles), you do not need flatMap or something like that, you can do this on a simple map using an array of js operators:

var transformed = [].concat(...result.map(item => item.subItems));

or in your case

httpResult$.map(result => [].concat(...result.map(item => item.subItems))

, , .

+1

map(), , concatAll() ( Observables, . Observable ):

var data = [{
    id : 1,
    name : "Item 1",
    subItems : [
        { id : 1, name : "SubItem 1" },
        { id : 2, name : "SubItem 2" }
    ]
}, {
    id : 2,
    name : "Item 2",
    searchProfiles : [
        { id : 3, name : "SubItem 3" },
        { id : 4, name : "SubItem 4" }
    ]
}];

Observable.from(data)
    .map(item => {
        if (item.searchProfiles) {
            return item.searchProfiles;
        } else if (item.subItems) {
            return item.subItems
        }
    })
    .concatAll()
    .subscribe(val => console.log(val));

:

{ id: 1, name: 'SubItem 1' }
{ id: 2, name: 'SubItem 2' }
{ id: 3, name: 'SubItem 3' }
{ id: 4, name: 'SubItem 4' }

, , , toArray() .concatAll() .subscribe(...), :

[ { id: 1, name: 'SubItem 1' },
  { id: 2, name: 'SubItem 2' },
  { id: 3, name: 'SubItem 3' },
  { id: 4, name: 'SubItem 4' } ]
+1

Source: https://habr.com/ru/post/1664381/


All Articles