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

如何从嵌套数组中按顺序提取元素生成目标数组?

嵌套数组拆分解决方案

原始输入数组

const initArray = [
  {
    '18888': [
      {
        unitId: 1,
        venueId: 18888,
      },
      {
        unitId: 2,
        venueId: 18888,
      },
    ],
  },
  {
    '19999': [
      {
        unitId: 3,
        venueId: 19999,
      },
      {
        unitId: 4,
        venueId: 19999,
      },
    ],
  },
];

需求说明

从initArray中提取两个目标数组:

  • resultArray1:依次取每个子对象中数组的第1个元素(索引0)
  • resultArray2:依次取每个子对象中数组的第2个元素(索引1)

目标结果如下:

const resultArray1 = [
  { unitId: 1, venueId: 18888 },
  { unitId: 3, venueId: 19999 },
];

const resultArray2 = [
  { unitId: 2, venueId: 18888 },
  { unitId: 4, venueId: 19999 },
];

你的尝试代码问题分析

你当前的代码逻辑过于冗余,引入了不必要的reduce和filter操作,而且qwe[0]可能因为数组长度不足导致索引越界或返回undefined,进而引发问题。其实可以直接遍历原始数组,提取对应位置的元素即可。

可行解决方案

方案一:遍历提取(直观易懂)

const resultArray1 = [];
const resultArray2 = [];

initArray.forEach(item => {
  // 取出每个子对象中的数组(无需关心键名)
  const unitList = Object.values(item)[0];
  // 安全提取对应位置元素并加入目标数组
  if (unitList[0]) resultArray1.push(unitList[0]);
  if (unitList[1]) resultArray2.push(unitList[1]);
});

console.log(resultArray1);
console.log(resultArray2);

方案二:使用map函数(简洁写法)

const resultArray1 = initArray.map(item => Object.values(item)[0][0]);
const resultArray2 = initArray.map(item => Object.values(item)[0][1]);

// 若担心数组长度不足产生undefined,可添加过滤:
// const resultArray1 = initArray.map(item => Object.values(item)[0][0]).filter(Boolean);
// const resultArray2 = initArray.map(item => Object.values(item)[0][1]).filter(Boolean);

方案三:TypeScript类型安全版本

如果用TypeScript开发,可添加类型定义和安全判断避免报错:

interface Unit {
  unitId: number;
  venueId: number;
}

type VenueUnits = { [key: string]: Unit[] };

const initArray: VenueUnits[] = [
  {
    '18888': [
      { unitId: 1, venueId: 18888 },
      { unitId: 2, venueId: 18888 },
    ],
  },
  {
    '19999': [
      { unitId: 3, venueId: 19999 },
      { unitId: 4, venueId: 19999 },
    ],
  },
];

const resultArray1: Unit[] = [];
const resultArray2: Unit[] = [];

initArray.forEach(item => {
  const unitList = Object.values(item)[0];
  if (unitList?.length >= 1) resultArray1.push(unitList[0]);
  if (unitList?.length >= 2) resultArray2.push(unitList[1]);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 08:47:33