2017-04-24 85 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);