在角度 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}]

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


慕尼黑5688855
浏览 109回答 2
2回答

DIEA

您正在吞噬前一个过滤器的结果,您应该跟踪,例如使用函数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));

偶然的你

也许这个?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++){&nbsp; if(component[i].type == 'Comp1' || component[i].type == 'Comp2'){&nbsp; &nbsp; out.push(component[i]);&nbsp; }}console.log(out);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript