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

如何过滤JavaScript对象数组,保留含有效爱好的完整层级结构?

过滤人员爱好数组的最佳实现方式

我有一个包含人员信息的对象数组,需要过滤处理后返回结构一致的新数组,仅保留每个人员hobbies中category里isHobbie为true的条目,请问最佳实现方式是什么?

原始数据

const people = [
  {
    id: 1,
    hobbies: [
      { extraSports: false, category: [{ isHobbie: true, hobbieType: 'paint' }, { isHobbie: false, hobbieType: 'work' }] },
      { extraSports: true, category: [{ isHobbie: false, hobbieType: 'work' }, { isHobbie: true, hobbieType: 'soccer' }] }
    ]
  },
  {
    id: 2,
    hobbies: [
      { extraSports: false, category: [{ isHobbie: true, hobbieType: 'draw' }, { isHobbie: false, hobbieType: 'work' }] },
      { extraSports: true, category: [{ isHobbie: true, hobbieType: 'tennis' }, { isHobbie: true, hobbieType: 'soccer' }] }
    ]
  }
]

预期结果

const peopleWithHobbies = [
  {
    id: 1,
    hobbies: [
      { extraSports: false, category: [{ isHobbie: true, hobbieType: 'paint' }] },
      { extraSports: true, category: [{ isHobbie: true, hobbieType: 'soccer' }] }
    ]
  },
  {
    id: 2,
    hobbies: [
      { extraSports: false, category: [{ isHobbie: true, hobbieType: 'draw' }] },
      { extraSports: true, category: [{ isHobbie: true, hobbieType: 'tennis' }, { isHobbie: true, hobbieType: 'soccer' }] }
    ]
  }
]

现有实现的问题

我之前写的代码:

people.flatMap(person => person.hobbies).flatMap(hobbies => hobbies.category).filter(category => category.isHobbie == true)

这段代码用了两次flatMap,会把所有层级扁平化,最终得到的是一个仅包含符合条件的category条目的一维数组,完全丢失了原有的人员和hobbies层级结构,不符合需求。

最佳实现方式

要保持原数组结构,需要用嵌套的map配合filter来处理,既保留原有层级,又过滤掉不符合条件的条目:

const peopleWithHobbies = people.map(person => ({
  // 保留人员的所有原有属性
  ...person,
  // 重新处理hobbies数组
  hobbies: person.hobbies.map(hobby => ({
    // 保留hobby的其他属性(比如extraSports)
    ...hobby,
    // 过滤category中isHobbie为true的条目
    category: hobby.category.filter(item => item.isHobbie)
  }))
}));

实现说明

  1. 外层map遍历每个人员对象,通过扩展运算符...person复制原对象的所有属性(比如id),然后重写hobbies属性;
  2. 内层map遍历每个hobby对象,同样用扩展运算符保留extraSports等属性,只重写category;
  3. 对每个category数组使用filter,仅保留isHobbie为true的条目;
  4. 整个过程不会修改原数组,返回的是全新的结构一致的数组。

内容的提问来源于stack exchange,提问作者Mat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 07:10:30