Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/452.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在列表中为每个“type”属性显示一项?_Javascript_Typescript - Fatal编程技术网

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

Javascript 如何在列表中为每个“type”属性显示一项?,javascript,typescript,Javascript,Typescript,我正在写一份申请书。在其中一个视图中,可以选择显示类别Product的项目列表,该列表可以通过多种方式进行过滤 export class Product { constructor( public id: number, public type: number ) { } } 我想做的是: 在产品的属性中有类型。我如何过滤它们,以便每种类型只获得一个项目?我要做的是使用这个函数,但我不知道如何在括号中编写逻辑语句 filterItemsOnePerType() {

我正在写一份申请书。在其中一个视图中,可以选择显示类别
Product
的项目列表,该列表可以通过多种方式进行过滤

export class Product {
  constructor(
    public id: number,
    public type: number
  ) {
  }
}
我想做的是:

产品
的属性中有
类型
。我如何过滤它们,以便每种类型只获得一个项目?我要做的是使用这个函数,但我不知道如何在括号中编写逻辑语句

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}]

您可能希望使用集合排除重复项。

您可以使用
数组。reduce
方法将其过滤掉

const数组=[
{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((结果,项)=>{
const isFound=result.find(({type})=>item.type==type);
如果(isFound){
返回结果;
}
返回[…结果,项目];
}, []);

控制台日志(结果)什么是输入,什么是预期的输出?@goto1
此.products
是Product类的对象数组。我想要得到的是Product类对象的数组(
this.filteredProducts
),其中的
type
属性中没有重复。我想要的是一个输入和输出示例,我们可以使用它,而不仅仅依赖于您的描述。@goto1您的意思是这样的示例吗?是的,这仅仅是一个好奇:即使类型是字符串而不是数字,这也能工作吗?
 this.filteredProducts = Object.assign([], this.products).filter(
   (types => item =>  !types.has(item.type) && types.add(item.type))(new Set)
 );