【问题标题】:Angular 2 filter out repeating dropdown occurrencesAngular 2过滤掉重复的下拉菜单
【发布时间】:2017-09-21 03:45:18
【问题描述】:

有谁知道如何过滤掉 am angular 2 下拉列表中的报告结果。我目前正在尝试在模板 *ngFor 中执行此操作,但没有运气。我也会尝试定制管道。数据来自 JSON 数组。在下面的对象中,我试图只显示“国有实体”的一个实例

我的数据对象

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>

【问题讨论】:

  • 感谢您的回复,但感谢 Yoav Schniederman 来自此链接 stackoverflow.com/questions/41867448/… transform(){ if(this.items!== undefined &amp;&amp; this.items!== null){ console.log(_.uniqBy(this.items, 'currentBUName')); this.currentBUvals = _.uniqBy(this.items, 'currentBUName'); return _.uniqBy(this.items, 'currentBUName'); } return this.items; }

标签: arrays angular typescript ionic2 angularjs-filter


【解决方案1】:

其他答案很好,但您可以这样做的一种方法是根据一些更通用的实用函数来定义它

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);

【讨论】:

    【解决方案2】:

    为什么不使用数组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

    【讨论】:

      【解决方案3】:

      当您设置items 的值时,使用过滤器函数仅获取唯一值。可以这样做:

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

      注意:如果此数据来自服务器,那么在服务器端执行此过滤以减少通过网络传输的重复信息量会更有意义。

      【讨论】:

        猜你喜欢
        • 2023-03-11
        • 2020-07-11
        • 2019-05-13
        • 2012-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多