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