2017-04-24 87 views
0

有誰知道如何過濾出出現在angular 2下拉列表中的報告結果。我目前正試圖在模板* ngFor中做到這一點,但沒有運氣。我也會嘗試一個自定義管道。數據來自JSON數組。在下面的對象我想只顯示的「國有實體」Angular 2過濾掉重複出現的下拉菜單

Result in dropdown

我的數據對象的一個​​實例

items[ 
     { 
     "currentBUName":"Financial Services" 
     } 
     { 
     "currentBUName":"State Owned Entities" 
     } 
     { 
     "currentBUName":"State Owned Entities" 
     } 
    ] 

我的TS碼提取

<ion-item> 
    <ion-label>Please select current business unit</ion-label> 
     <ion-select [(ngModel)]="selectedValue"> 
      <ion-option *ngFor="let indexx of this.items;"[value]="indexx">{{indexx.currentBUName}}</ion-option> 
     </ion-select> 
    </ion-item> 
+0

感謝您的回覆,但我最終使用了這個函數t hanks從這個鏈接Yoav Schniederman http://stackoverflow.com/questions/41867448/in-angular2-ngfor-iteration-how-do-i-output-only-unique-values-from-the-array'transform() {this.items!== undefined && this.items!== null} console.log(_。uniqBy(this.items,'currentBUName')); this.currentBUvals = _.uniqBy(this.items,'currentBUName'); return _.uniqBy(this.items,'currentBUName'); } return this.items; }' – eohdev

回答

0

當你設置值爲items使用過濾函數只能獲取唯一值。這是可以做到像這樣:

this.items = this.items.filter((v, i, arr) => arr.indexOf(v) === i); 

注意:如果這個數據是來自服務器那就更有意義,這樣做過濾服務器端的減少將通過線路傳來的重複信息量。

0

爲什麼不使用數組filter

items = [ 
    { 
    "currentBUName":"Financial Services" 
    } 
    { 
    "currentBUName":"State Owned Entities" 
    } 
    { 
    "currentBUName":"State Owned Entities" 
    } 
] 
uniqueItems = items.filter(function(item, pos) { 
    return items.indexOf(item) == pos; 
}) 

然後用uniqueItems代替

0

其他的答案是好的,但你可以做到這一點的一種方式是在一些更一般的效用函數來定義它

function groupBy<T>(values: T[], keySelector: (value: T) => string): {[key: string]: T[]} { 
    return values 
     .map(value => ({ key: keySelector(value), value })) 
     .reduce((groups, { key, value }) => ({ 
     ...groups, 
     [key]: groups[key] && groups[key].concat(value) || [value] 
     }), {}); 
} 

function distinctBy<T>(values: T[], keySelector: (value: T) => string): T[] { 
    const groups = groupBy(values, keySelector); 
    return Object.values(groups).map(([representative]) => representative); 
} 

然後,你可以寫

this.items = distinctBy(incomingItems, item => item.currentBUName);