Javascript过滤嵌套数组

时间:2019-02-06 14:30:10

标签: javascript angular typescript

我正在尝试对Angular应用程序中的对象数组内的嵌套数组进行过滤。这是组件代码的片段-

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' }] }
];

我要实现的目标是,例如,我搜索m5的结果应该是-

var teams = [
  { name: 'Team1', members: [] }, 
  { name: 'Team2', members: [{ name: 'm5' }] }, 
  { name: 'Team3', members: [] }
];

所以我有teamsfilteredTeams属性,在搜索功能中,我正在做-

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;
  })
}

现在这在某种程度上确实起作用了,但是因为我要替换成员,这会破坏每次调用时的数组(如果有意义)。我知道为什么会这样,但是我的问题是实现此过滤器的最佳方法是什么?

4 个答案:

答案 0 :(得分:3)

您非常亲密,唯一做错的是变异 teams

中的源对象

基本上,您可以使用spread运算符生成一个新条目,然后返回带有新值的全新数组。

const 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' }] }
];

const value = 'm5';

const result = this.teams.map(t => {
  const members = t.members.filter(d => d.name.toLowerCase().includes(value));
  return { ...t, members };
})

console.log(result)

答案 1 :(得分:0)

检查此。不用硬编码的m5传递您的价值。

const 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' }] }
];

const filteredTeams = teams.map(team => ({ name: team.name, members: team.members.filter(member => member.name.includes('m5')) }));

console.log(filteredTeams);

答案 2 :(得分:0)

您正在变异原始对象,但可以将新属性赋给结果对象以进行映射。

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' }] }],
    result = teams.map(o => Object.assign(
        {},
        o,
        { members: o.members.filter(({ name }) => name === 'm5') }
    ));
    
console.log(result);
console.log(teams);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)

尝试首先分离您的过滤器功能:

const filterTeamMembers = (teams, filterArr) => {
    const useFilter = filterArr.map(x => x.toLowerCase());

    return teams.map(team => ({
        ...team,
        members: team.members.filter(member => useFilter.includes(member.name))
    }))
};
// =========== And then:

onSearchChange(event: any): void {
    let value = event.target.value;
    this.filteredTeams = filterTeamMembers(this.teams, [value]);
}