You need to enable JavaScript to run this app. 如何从JavaScript多维对象数组中提取所有内层units的id生成新数组
优惠活动
大模型
产品
解决方案
定价
更多

如何从JavaScript多维对象数组中提取所有内层units的id生成新数组

最优实现方案

直接使用flatMap完成映射+展平操作,代码简洁且性能最优,仅需一次遍历即可得到结果:

// 你的数据源
const sourceData = [
  {
    units: [
      { id: 10000282, name: "Group 1" },
      { id: 10000340, name: "Group 2" },
      { id: 10000341, name: "Group 3" },
    ],
  },
  {
    units: [
      { id: 10000334, name: "Group 4" },
    ],
  },
];

// 核心代码
const ids = sourceData.flatMap(item => item.units.map(unit => unit.id));

输出结果为:[10000282, 10000340, 10000341, 10000334]

旧环境兼容方案

如果需要兼容不支持flatMap的低版本JS运行环境,可以用reduce替代实现,效果完全一致:

const ids = sourceData.reduce((result, current) => {
  return result.concat(current.units.map(unit => unit.id));
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 09:09:01