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

如何从复杂深度嵌套的对象数组中提取questions数组内所有对象

提取多层嵌套数组中所有questions对象的实现方案

你可以根据数据结构是否会发生变动,选择以下两种方案:

  • 结构固定场景优先选flatMap打平:性能最高,代码最简洁
    你给出的示例数据层级固定为:根学科数组 -> chapters章节数组 -> sections小节数组 -> questions题目数组,直接用flatMap逐层打平即可:

    const arr2 = arr1.flatMap(subject => 
      subject.chapters.flatMap(chapter => 
        chapter.sections.flatMap(section => section.questions)
      )
    );
    

    flatMap会在映射后自动打平1层数组,三次调用刚好可以把所有分散在各层级的questions对象合并成一维数组,输出和你预期的arr2结构完全一致。

  • 结构可能变动场景选递归提取:不需要关心嵌套层级,容错性高
    如果后续数据可能新增嵌套层级,不需要调整遍历逻辑,写一个递归函数遍历所有节点,只要识别到键名为questions的数组就收集内部元素即可:

    function collectQuestions(data, result = []) {
      if (Array.isArray(data)) {
        data.forEach(item => collectQuestions(item, result));
        return result;
      }
      if (data && typeof data === 'object') {
        for (const [key, value] of Object.entries(data)) {
          if (key === 'questions' && Array.isArray(value)) {
            result.push(...value);
            continue;
          }
          collectQuestions(value, result);
        }
      }
      return result;
    }
    
    const arr2 = collectQuestions(arr1);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 10:21:25