我有一个对象数组,并且正在像这样对属性名称“用户名”进行过滤。
array = [{
"id": 1,
"username": "admin",
"roles": [{
"name": "Administrator"
},
{
"name": "agent"
}
]
},
{
"id": 2,
"username": "admin2",
"roles": [{
"name": "Administrator2"
},
{
"name": "agent2"
}
]
},
{
"id": 3,
"username": "admin3",
"roles": [{
"name": "Administrator3"
},
{
"name": "agent3"
}
]
}
]
过滤器功能就是这样
transform(array: any, valueToSearch: string): any[] {
return array.filter(e =>
e.username.toLowerCase().indexOf(valueToSearch.toLowerCase())
!== -1);
}
一切正常,但是现在我想针对对象中“角色”数组中的属性名称“名称”进行过滤。例如,我想返回一个对象,该对象的“角色”数组包含“名称” = agent3,因此它应该返回整个对象,该对象位于我的示例的最后一个位置。我尝试过
return agents.filter(e => e.roles.filter(ee =>
ee.valueToSearch.toLowerCase()) !== -1));
但是没有用。
这是dmeo https://stackblitz.com/edit/angular-txchxs?embed=1&file=src/app/agentFilter.pipe.ts
答案 0 :(得分:1)
根据您在问题中给出的示例,我能够像这样更改您现有的功能,我希望这是您的要求。
ngOnInit() {
this.transform(this.array,'agent3');
}
transform(array: any, valueToSearch: string): any[] {
return this.array.filter(e => {
e.roles.filter(ee => {
if(ee.name.toLowerCase() === valueToSearch.toLowerCase() ) {
console.log(e);
this.finalResult = e;
}
})
})
}
正在工作的Stackblitz:https://stackblitz.com/edit/angular-uzgni7
答案 1 :(得分:0)
myarray = [{
"id": 1,
"username": "admin",
"roles": [{
"name": "Administrator"
},
{
"name": "agent"
}
]
},
{
"id": 2,
"username": "admin2",
"roles": [{
"name": "Administrator2"
},
{
"name": "agent2"
}
]
},
{
"id": 3,
"username": "admin3",
"roles": [{
"name": "Administrator3"
},
{
"name": "agent3"
}
]
}
];
function myFunction(){
var filtered= myarray.filter((obj)=>{
return obj.username.match(new RegExp(document.getElementById('search').value,'ig'));
});
console.log(filtered);
};
<input type="text" id="search" onkeyup="myFunction()"/>