ES6如何过滤对象数组,筛选teams为空或不含指定值的项
错误原因分析
- 第一种写法的问题:
Array.includes()对引用类型做的是全等判断,你代码里传入的{ name: "oliver" }是新创建的对象,和数组里已有的对象内存地址不同,所以永远返回false,取反后所有非空teams的项都会被判定为符合条件。 - 第二种写法的问题:你的
teams是二维数组,match.teams.some遍历到的每个team是成员数组,不是成员对象,所以team.name必然是undefined,判断永远不成立,取反后所有非空teams的项也都会被判定为符合条件。
正确实现代码
const result = matches.filter(match => { // teams为空直接保留 if (match.teams.length === 0) return true // 两层遍历判断是否存在name为oliver的成员 const hasOliver = match.teams.some(team => { return team.some(member => member.name === 'oliver') }) // 不存在oliver才保留 return !hasOliver })
也可以简化为一行写法:
const result = matches.filter(match => match.teams.length === 0 || !match.teams.some(team => team.some(m => m.name === 'oliver')))
运行后得到的result就是你预期的match为"1"和"3"的两个对象。
内容的提问来源于stack exchange,提问作者agusgambina
相关产品推荐
相关产品推荐

