2017-08-07 50 views
2

嵌套数组使用RxJs可观察到中流的格式如下:附加参数从Obervable

{ 
    term: 'one', 
    sources: [ 
     { 
     name: 'google' 
     }, 
     { 
     name: 'yahoo' 
     } 
    ] 
} 

我希望把它变成格式:

{ 
    sources: [ 
     { 
     name: 'google', 
     id: 'one' 
     }, 
     { 
     name: 'yahoo', 
     id: 'one' 
     } 
    ] 
} 

所以我喜欢将该术语追加到sources数组中的每个元素上。 最后,我真的很喜欢他们的发射正确格式化的数组元素。 我猜这是用mergeMap来发射每个数组el的事件,但我挣扎!

RxJs v5.4.2

回答

1

你是正确的,你可以使用mergeMap/flatMap实现这一目标。 然后使用.from()一次发送一个源。

let data = { 
    term: 'one', 
    sources: [ 
     { 
      name: 'google' 
     }, 
     { 
      name: 'yahoo' 
     } 
    ] 
}; 

let obs$ = Observable.of(data) // mimicking whatever your observable sequence is 
    .flatMap(res => { 
     // assign id to each item in sources array 
     res.sources.forEach(item => { 
      item.id = res.term; 
     }); 

     return Observable.from(res.sources); 
    }); 

obs$.subscribe(res => { 
    console.log('subscribe result', res); 
}); 

// output is 
// subscribe result {name: 'google', id: 'one'} 
// subscribe result {name: 'yahoo', id: 'one} 
+1

伟大的东西,谢谢! 由于版本RxJs 只是不得不将flatMap更改为mergeMap,但工作了一种享受。 – librsean

1

您可以使用concatMap转换的扁平化Observablemap创建一个新的可观测与nameterm财产的关键。

var dataLists = Rx.Observable.from([{ 
 
    term: 'one', 
 
    sources: [ 
 
     { 
 
     name: 'google' 
 
     }, 
 
     { 
 
     name: 'yahoo' 
 
     } 
 
    ] 
 
}]); 
 

 

 
dataLists = dataLists.concatMap(function(dataList) { 
 
    return dataList.sources.map(function(source){ 
 
    source.term = dataList.term; 
 
    return source; 
 
    }) 
 
}); 
 

 
dataLists.forEach(function(dataList){ 
 
    console.log(dataList); 
 
})
<script src="https://unpkg.com/@reactivex/[email protected]/dist/global/Rx.js"></script>