【问题标题】:How to select distinct property values of a list of object in Angular [duplicate]如何在Angular中选择对象列表的不同属性值[重复]
【发布时间】:2020-02-26 13:17:02
【问题描述】:

我有以下对象列表:

var data = [
    {
        "AcctId": 100,
        "Value": true
    },
    {
        "AcctId": 200,
        "Value": false
    }
]

我想像这样选择不同的 AcctId:

Output: [100, 200]

我尝试过使用角度滤镜方法:

var newData = data.filter(r => r.AcctId);

但是,它返回与输入相同的列表。谁能指导我做错了什么?

【问题讨论】:

  • data.map(v => v.AcctId)
  • data.filter(r => r.AcctId) 将只保留具有 ID 值且该值非零的任何内容。

标签: javascript angular


【解决方案1】:

试试这样:

Working Demo

this.result = Array.from(new Set(this.data.map(x => x.acctId)));

或者,

 constructor() {
    this.result = this.GetDistinctValues(this.data, "acctId").map(x => x.acctId);
  }

  GetDistinctValues(Source: Array<any>, FilterKey: string = null): Array<any> {
    let DistinctArray = [];
    try {
      Source.forEach(e => {
        if (FilterKey !== null && FilterKey !== undefined && FilterKey !== "") {
          if (
            DistinctArray.filter(DE => DE[FilterKey] === e[FilterKey]).length <=
            0
          )
            DistinctArray.push(e);
        } else {
          if (DistinctArray.indexOf(e) === -1) DistinctArray.push(e);
        }
      });
    } catch (error) {
      DistinctArray = [];
    }
    return DistinctArray;
  }

Demo 2

【讨论】:

    【解决方案2】:

    或者是lodash的方式:

    lodash.uniq(this.data.map(x => x.acctId));
    

    【讨论】:

      【解决方案3】:

      你可以使用 rxjs 库来

      import { of } from 'rxjs';
      import { distinct } from 'rxjs/operators';
      
      interface Person {
      age: number,
      name: string
      }
      
      of<Person>(
          { age: 4, name: 'Foo'},
          { age: 7, name: 'Bar'},
          { age: 5, name: 'Foo'},
      ).pipe(
          distinct((p: Person) => p.name),
      )
      .subscribe(x => console.log(x));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-22
        • 1970-01-01
        • 2022-01-24
        • 2016-10-06
        • 2022-01-12
        • 2021-10-17
        • 2023-04-07
        • 2019-03-15
        相关资源
        最近更新 更多