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

如何遍历含动态键的嵌套对象,筛选考试通过的学生姓名列表

从动态键对象中筛选考试通过的学生姓名

首先明确你的原始数据结构:

const schoolArr = { 
  class10: { studentInfo: {name: 'John'}, exam: {result: 'pass'} }, 
  class11: { studentInfo: {name: 'Alis'}, exam: {result: 'pass'} }, 
  class12: { studentInfo: {name: 'Nick'}, exam: {result: 'fail'} } 
};

下面提供几种实用的实现方式,都能处理这些动态的班级键:

方法1:简洁链式调用(推荐)

用Object.values()直接获取所有班级的信息对象,接着过滤出考试通过的记录,最后提取学生姓名:

const passedStudents = Object.values(schoolArr)
  // 筛选考试通过的班级
  .filter(classItem => classItem.exam.result === 'pass')
  // 可选:过滤掉没有姓名的异常数据
  .filter(classItem => classItem.studentInfo?.name)
  // 提取姓名
  .map(classItem => classItem.studentInfo.name);

console.log(passedStudents); // 输出: ['John', 'Alis']

方法2:遍历键名处理

如果需要同时获取班级的键名(比如class10),可以先用Object.keys()拿到所有动态键,再逐个处理:

const passedStudents = [];
// 获取所有班级的键名数组
const classKeys = Object.keys(schoolArr);

for (const key of classKeys) {
  const classItem = schoolArr[key];
  // 判断考试通过且存在姓名
  if (classItem.exam.result === 'pass' && classItem.studentInfo.name) {
    passedStudents.push(classItem.studentInfo.name);
  }
}

console.log(passedStudents); // 输出: ['John', 'Alis']

方法3:传统for...in循环

这是兼容性较好的遍历方式,记得加hasOwnProperty避免遍历到原型链上的属性:

const passedStudents = [];

for (const key in schoolArr) {
  // 确保是对象自身的属性
  if (schoolArr.hasOwnProperty(key)) {
    const classItem = schoolArr[key];
    if (classItem.exam.result === 'pass' && classItem.studentInfo.name) {
      passedStudents.push(classItem.studentInfo.name);
    }
  }
}

console.log(passedStudents); // 输出: ['John', 'Alis']

这些方法的核心都是遍历对象的所有可枚举属性,不管键名是静态写死还是动态生成的,都能覆盖到,完美解决你遇到的动态键迭代问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:00:32