You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 10:42:01