I have a nested array inside an array of objects in my Angular app that I'm attempting to filter. Here is a snippet of the component code:
var teams = [
{ name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name: 'm3' }] },
{ name: 'Team2', members: [{ name: 'm4' }, { name: 'm5' }, { name: 'm6' }] },
{ name: 'Team3', members: [{ name: 'm7' }, { name: 'm8' }, { name: 'm9' }] }
];
My goal is to filter based on a search query, for example if I search for m5
, I want my result to look like this:
var teams = [
{ name: 'Team1', members: [] },
{ name: 'Team2', members: [{ name: 'm5' }] },
{ name: 'Team3', members: [] }
];
To achieve this, I have properties teams
and filteredTeams
, and in my search function I am doing the following:
onSearchChange(event: any): void {
let value = event.target.value;
this.filteredTeams = this.teams.map(t => {
t.members = t.members.filter(d => d.name.toLowerCase().includes(value));
return t;
})
}
While this approach works partially, it replaces the members array on each call which is not ideal. I understand the issue here, but I'm unsure about the best way to implement this filter. Any suggestions?