You need to enable JavaScript to run this app. 如何过滤数组并基于指定对象键创建合并后的新数组
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤数组并基于指定对象键创建合并后的新数组

实现方案

核心逻辑

不需要复杂的筛选判断,只需要两个操作:

  • 遍历外层数组的每一个父级对象
  • 取出每个对象挂载的items子数组,把所有子数组的内容拼接为一维数组
    如果担心items子数组里有其他冗余字段,可以在提取过程中只保留id属性,保证输出结构完全匹配要求。

简洁实现(原生JS)

用flatMap方法可以一行完成子数组提取和扁平化,和当前场景的适配度最高:

// 源数组
const sourceList = [
  {
    "id": "carType",
    "items": [
      { "id": "SUV" },
      { "id": "Compact" }
    ]
  },
  {
    "id": "fuelType",
    "items": [
      { "id": "Gasoline" },
      { "id": "Hybrid" }
    ]
  }
]

// 合并提取
const targetList = sourceList.flatMap(parentItem => parentItem.items)

运行这段代码的输出和要求的目标结构完全一致。

兼容旧环境的写法

如果需要支持不兼容flatMap的运行环境,可以用reduce配合concat实现相同效果:

const targetList = sourceList.reduce((acc, current) => {
  return acc.concat(current.items)
}, [])

严格过滤冗余字段的写法

如果items里存在id以外的其他属性,可以在映射阶段只提取需要的id字段,保证输出纯净:

const targetList = sourceList.flatMap(parentItem =>
  parentItem.items.map(item => ({ id: item.id }))
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.18 12:24:05