Merge subarrays using Observables

后端 未结 2 1262
执笔经年
执笔经年 2020-12-02 03:06

I have this data structure:

[{
    id : 1,
    name : \"Item 1\",
    subItems : [{
            id : 1,
            name : \"SubItem 1\"
        },{
                 


        
2条回答
  •  执笔经年
    2020-12-02 03:44

    You want to first map() operator to extract only fields you need and them flatten the arrays of objects with concatAll() (it's a little trick with higher order Observables, see Subscribing to a nested Observable for more info):

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

    This prints to console:

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

    Alternatively, if you really want the output as a single array then you can add toArray() operator between .concatAll() and .subscribe(...) and you'll receive:

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

提交回复
热议问题