繁体   English   中英

如何在列表中为每个 `type` 属性显示一项?

[英]How to display one item per `type` attribute in a list?

我正在编写一个 Angular 8 应用程序。 在其中一个视图中,可以选择显示Product类的项目列表,并且可以通过多种方式过滤此列表。

export class Product {
  constructor(
    public id: number,
    public type: number
  ) {
  }
}

我想做的事:

Product的属性中有type 我如何过滤它们才能获得每种类型的项目 我会做的是使用这个函数,但我不知道如何在括号中编写逻辑语句。

filterItemsOnePerType() {
    this.filteredProducts = Object.assign([], this.products).filter(
      item => (... item.type ...)
    );
  }

请注意,将要选择的项目并不重要。 重要的是,在最终视图中,我不会看到类型之间有任何重复。

例子

我有一个产品清单:

[{id: 1, type:1},
 {id: 2, type:1},
 {id: 3, type:1},
 {id: 4, type:2},
 {id: 5, type:2},
 {id: 6, type:3},
 {id: 7, type:2}]

因此,我想获得的是以下列表:

[{id: 1, type:1},
 {id: 4, type:2},
 {id: 6, type:3}]
 this.filteredProducts = Object.assign([], this.products).filter(
   (types => item =>  !types.has(item.type) && types.add(item.type))(new Set)
 );

您可能希望使用 Set 来排除重复项。

您可以使用Array.reduce方法将其过滤掉。

 const array = [ { id: 1, type: 1 }, { id: 2, type: 1 }, { id: 3, type: 1 }, { id: 4, type: 2 }, { id: 5, type: 2 }, { id: 6, type: 3 }, { id: 7, type: 2 } ]; const result = array.reduce((result, item) => { const isFound = result.find(({ type }) => item.type === type); if (isFound) { return result; } return [...result, item]; }, []); console.log(result);

回到您的原始代码,您将执行以下操作:

filterItemsOnePerType() {
  this.filteredProducs = Object.assign([], this.producs).reduce(
    (result, item) => {
      const isFound = result.find(
        ({ type }) => item.type === type
      )
      if (isFound) return result

      return [...result, item]
    }, []
  )
}

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM