2017-04-01 39 views
0

甲流constains以下對象如何有條件地合併單個Observable流中的對象?

const data = [ 
    { type: 'gps', id: 1, val: 1 }, 
    { type: 'gps', id: 2, val: 2 }, 
    { type: 'speed', id: 2, val: 3 }, 
    { type: 'gps', id: 3, val: 4 }, 
    { type: 'speed', id: 4, val: 5 }, 
    { type: 'gps', id: 4, val: 6 }, 
    { type: 'gps', id: 5, val: 7 } 
] 

萬一ID相同,則對象被合併。如果沒有ID匹配時,物體會被忽略:

[ 
    [{type: 'gps', id:2, val:2}, { type: 'speed', id: 2, val: 3 }], 
    [{ type: 'speed', id: 4, val: 5 },{ type: 'gps', id: 4, val: 6 }] 
] 

我的想法是組具有相同類型的對象,有兩個新的流

Rx.Observable.from(data) 
    .groupBy((x) => x.type) 
    .flatMap((g) => ...) 
    .... 

,然後結束了合併/再次壓縮它們如果id是相等的。

我不知道如何在Rx中指定這個,我也不確定這是否是一種好方法。

回答

0

沒有必要拆分流並重新合併它。您可以使用scan收集的對象和filter出不符合那些調理

const data = [ 
 
    { type: 'gps', id: 1, val: 1 }, 
 
    { type: 'gps', id: 2, val: 2 }, 
 
    { type: 'speed', id: 2, val: 3 }, 
 
    { type: 'gps', id: 3, val: 4 }, 
 
    { type: 'speed', id: 4, val: 5 }, 
 
    { type: 'gps', id: 4, val: 6 }, 
 
    { type: 'gps', id: 5, val: 7 } 
 
] 
 

 
const generator$ = Rx.Observable.from(data) 
 

 
generator$ 
 
    .scan((acc, x) => { 
 
    if (R.contains(x.id, R.pluck('id', acc))) { 
 
     acc.push(x); 
 
    } else { 
 
     acc = [x] 
 
    } 
 
    return acc 
 
    }, []) 
 
    .filter(x => x.length > 1) 
 
    .subscribe(console.log)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.23.0/ramda.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.min.js"></script>

相關問題