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

如何遍历数组第二层元素,提取所有id生成单一结果数组?

提取Students数组中所有detail的id值

原始数组

const Students = [
  {
    "name":"Ashish",
    "lastname":"Boora",
    "detail":[
              {"id":1,"sid":3,"pid":5},
              {"id":2,"sid":4,"pid":6},
              {"id":7,"sid":8,"pid":9}
            ]
  },
  {
    "name":"Harsh",
    "lastname":"Deep",
    "detail":[
              {"id":11,"sid":13,"pid":15},
              {"id":12,"sid":14,"pid":16},
              {"id":17,"sid":18,"pid":19}
            ]
  },
  {
    "name":"Rajat",
    "lastname":"Sharma",
  },
  { 
    "name":"Sumit",
    "lastname":"Verma",
    "detail":[
              {"id":21,"sid":23,"pid":25},
              {"id":22,"sid":24,"pid":26},
              {"id":27,"sid":28,"pid":29}
            ]
  }
];

需求说明

遍历上述数组,提取所有detail子数组中的id值,生成单一结果数组:[1,2,7,11,12,17,21,22,27]。注意主数组中部分元素不含detail键,需跳过此类元素。

实现方案

方案1:使用reduce + concat

const ids = Students.reduce((acc, student) => {
  // 验证当前对象存在detail且为数组
  if (student.detail && Array.isArray(student.detail)) {
    return acc.concat(student.detail.map(item => item.id));
  }
  return acc;
}, []);

console.log(ids); // 输出:[1,2,7,11,12,17,21,22,27]

方案2:使用flatMap

flatMap可以直接将映射后的数组扁平化,代码更简洁:

const ids = Students.flatMap(student => {
  return student.detail ? student.detail.map(item => item.id) : [];
});

console.log(ids); // 输出:[1,2,7,11,12,17,21,22,27]

方案3:使用forEach循环

如果习惯更直观的循环写法,可以用双层forEach:

const ids = [];
Students.forEach(student => {
  if (student.detail && Array.isArray(student.detail)) {
    student.detail.forEach(item => ids.push(item.id));
  }
});

console.log(ids); // 输出:[1,2,7,11,12,17,21,22,27]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:06:26