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

如何从嵌套对象数组中返回指定类型的首个课程名称

从嵌套对象数组中获取第一个chemistry类型的课程名称

针对你这个需求——在嵌套对象数组里找到第一个类型为chemistry的课程并返回其名称,这里有个高效简洁的实现方案:

先回顾你的示例数据:

var mylist = [
 { "email" : null, "school" : "schoolA", "courses": [
 { "name" : 'ABC', "type" : "chemistry" },
 { "name" : 'XYZ', "type": "math" }
 ]
 },
 { "email" : null, "school": "schoolB" }
];

实现代码

var mylist = [
 { "email" : null, "school" : "schoolA", "courses": [
 { "name" : 'ABC', "type" : "chemistry" },
 { "name" : 'XYZ', "type": "math" }
 ]
 },
 { "email" : null, "school": "schoolB" }
];

let targetCourseName = null;

// 遍历外层数组,找到目标项就立刻停止
mylist.some(item => {
  // 先检查当前对象是否有courses数组,避免报错
  if (item.courses) {
    // 在课程数组里找第一个chemistry类型的课程
    const chemistryCourse = item.courses.find(course => course.type === "chemistry");
    if (chemistryCourse) {
      targetCourseName = chemistryCourse.name;
      return true; // 返回true终止后续遍历
    }
  }
  return false; // 没找到就继续下一个对象
});

console.log(targetCourseName); // 输出 "ABC"

代码逻辑说明

  • mylist.some(...):这个方法的特性是只要回调返回true,就会立即停止遍历整个数组,刚好契合我们“找第一个匹配项”的需求,不用做无用的遍历。
  • item.courses判断:防止某些对象没有courses属性时,调用find方法导致报错。
  • item.courses.find(...):在当前对象的课程列表里,精准定位第一个type为chemistry的课程对象,找到后直接返回该对象。
  • 如果全程没有找到符合条件的课程,targetCourseName会保持null,你可以根据需求改成空字符串或其他默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:50:41