我有一个对象数组存储在“组件”变量中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}]如何使其适用于多个值。提前致谢。
2 回答

DIEA
TA贡献1820条经验 获得超3个赞
您正在吞噬前一个过滤器的结果,您应该跟踪,例如使用函数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));

偶然的你
TA贡献1841条经验 获得超3个赞
也许这个?
var component=[{id:1,type:'Comp1'},{id:2,type:'Comp2'},{id:3,type:'Comp3'},{id:4,type:'Comp4'},{id:5,type:'Comp5'}];
var out = [];
for(i=0; i < component.length; i++){
if(component[i].type == 'Comp1' || component[i].type == 'Comp2'){
out.push(component[i]);
}
}
console.log(out);
添加回答
举报
0/150
提交
取消