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

JavaScript如何简化合并对象数组非空arr0子数组并按code键过滤

方案说明

你提供的原代码最终输出的是「所有非空arr0子数组合并后,剔除code值为imacode2的元素,再提取剩余元素的code字段组成的数组」,可以通过数组链式调用实现更简洁的写法,全程不需要额外声明冗余中间变量:

简洁实现代码

const array = [
  {
    id: 1,
    text: 'stuff1',
    arr0: [
      {id:1, code: 'imacode1'},
      {id:2, code: 'imacode2'},
    ]
  },
  {
    id: 2,
    text: 'stuff2',
    arr0: [
      {id:3, code: 'imacode3'},
      {id:4, code: 'imacode4'},
    ]
  },
  {
    id: 3,
    text: 'stuff3',
    arr0: []
  }
]

const result = array
  // flatMap自动完成提取arr0 + 摊平操作,空arr0会自动被过滤
  .flatMap(item => item.arr0)
  // 过滤掉code为imacode2的项
  .filter(item => item.code !== 'imacode2')
  // 提取code字段
  .map(item => item.code)

console.log(result)
// 输出:['imacode1', 'imacode3', 'imacode4']

逻辑对应说明

  • 用flatMap替代了你原来的「循环收集非空arr0 + 手动flat摊平」的两步操作,空数组会被自动忽略,不需要额外判断arr0.length
  • 后续的过滤和字段提取直接链式调用即可,不需要嵌套循环判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:36:03