2017-03-08 61 views
2

訂閱上的GroupedObservable我有對象的數組像follwing:使用在地圖

private questions: Question[] = [ 
    { 
     title: "...", 
     category: "Technologie", 
     answer: `...` 
    }, 
    { 
     title: "...", 
     category: "Technologie", 
     answer: `...` 
    }, 
    { 
     title: "...", 
     category: "eID", 
     answer: `...` 
    } 
]; 

我想按類別組他們,基於值過濾它們並返回其結果作爲陣列。目前,我使用的是這樣的:

Observable 
    .from(this.questions) 
    .groupBy(q => q.category) 
    .map(go => 
    { 
     let category: Category = { title: go.key, questions: [] }; 

     go.subscribe(d => category.questions.push(d)); 

     return category; 
    }) 
    .filter(c => c.title.toLowerCase().indexOf(value.toLowerCase()) >= 0 || c.questions.filter(q => q.title.toLowerCase().indexOf(value.toLowerCase()) >= 0).length > 0) 
    .toArray() 

這個發現與類別標題中值,但沒有一個在這個問題稱號值的問題。我認爲這是因爲我在map中使用subscribe,因此,filter方法中尚未提供這些問題,所以我想知道在進入filter之前是否有可能等待subscribe結束。我的研究指出我flatMap,但我無法做到我想要的。

編輯

我想通了,我可以解決這樣的問題:

Observable 
    .from(this.questions) 
    .filter(q => q.category.toLowerCase().indexOf(value.toLowerCase()) >= 0 || q.title.toLowerCase().indexOf(value.toLowerCase()) >= 0) 
    .groupBy(q => q.category) 
    .map(go => 
    { 
     let category: Category = { title: go.key, questions: [] }; 

     go.subscribe(d => category.questions.push(d)); 

     return category; 
    })    
    .toArray() 

但我仍然有興趣在回答。

回答

0

當你使用groupBy時,你會得到一個可以用concatMap,mergeMap,switchMap等操作符展開的分組觀察值。在這些操作符中,可以爲每個類別單獨轉換分組的觀察值,即將問題一起收集到一個數組中隨着減少,然後用地圖創建所需的對象。

Observable 
     .from(questions) 
     .groupBy(q => q.category) 
     .mergeMap(go => { 
      return go.reduce((acc, question) => { acc.push(question); return acc; }, []) 
       .map(questions => ({ title: go.key, questions })); 
     }) 
     .filter(c => "...") 
     .toArray()