首页 > 解决方案 > 在角度 6 中过滤具有多个值的相同键的数组对象

问题描述

我有一个对象数组存储在“组件”变量中

component=[{id:1,type:Comp1},{id:2,type:Comp2},{id:3,type:Comp3},{id:4,type:Comp4},{id:5,type:Comp5}]

我想按类型“Comp1”和“Comp2”过滤它。我尝试了以下代码

this.filterComponent=[{id:1,type:Comp1},{id:2,type:Comp2}];
for(let i=0;i<this.filterComponent.length;i++)
 this.component=  this.component.filter(ob => ob.type == this.filterComponenet[i].type)

但它仅适用于单个值(如果过滤组件仅包含一个对象)。例如,

this.filterComponent=[{id:1,type:Comp1}]

如何使其适用于多个值。提前致谢。

标签: javascriptangular

解决方案


您正在吞噬前一个过滤器的结果,您应该跟踪,例如使用函数concat甚至使用附加数组。

您还可以使用以下功能filter

this.filterComponent = [{id:1,type:Comp1},{id:2,type:Comp2}];
this.component = this.component.filter(({type}) => this.filterComponenet.some(({type: t}) => t === type));

推荐阅读