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

TypeScript中遍历JSON内部键值对遇undefined问题及访问需求

解决嵌套JSON对象的遍历问题

问题分析

你遇到的undefined问题,核心原因大概率是两个:

  1. this指向错误:在普通函数中this没有指向包含jsonData的对象,导致this.jsonData或this.jsonData[prop]无法正确获取值。
  2. 数据未正确初始化:如果你的jsonData是从JSON字符串转换而来,未执行JSON.parse()解析,会导致它还是字符串而非可遍历的对象。

另外,你的JSON是多层嵌套结构(对象→数组→对象→数组→对象),直接遍历顶层键值无法获取内部的morning/start_time等数据,需要递归或多层遍历。

解决方案

1. 先确保数据是可遍历的对象

如果你的数据是JSON字符串,先解析为JavaScript对象:

// 示例JSON字符串
const jsonStr = `{
    "Monday": [{"morning": [{"start_time": "02:00", "end_time": "07:30"}], "afternoon": [{"start_time": "02:00", "end_time": "05:00"}], "evening": [{"start_time": "02:30", "end_time": "07:00"}]},],
    "Tuesday": [{"morning": [{"start_time": "02:00", "end_time": "07:30"}], "afternoon": [{"start_time": "02:00", "end_time": "05:00"}], "evening": [{"start_time": "02:30", "end_time": "07:00"}]}]
}`;

// 解析为对象
const jsonData = JSON.parse(jsonStr);

2. 修复this指向问题

如果是在类组件或回调函数中,先将this.jsonData赋值给变量,避免this指向错误:

// 保存正确的数据源
const data = this.jsonData; // 确保this此时指向包含jsonData的对象

// 遍历顶层日期键
for (const dayKey in data) {
  console.log(`日期: ${dayKey}`);
  // 日期对应的值是数组,遍历数组内的每日时段对象
  data[dayKey].forEach(dayObj => {
    // 遍历时段(morning/afternoon/evening)
    for (const periodKey in dayObj) {
      console.log(`  时段: ${periodKey}`);
      // 时段对应的值是数组,遍历时间对象
      dayObj[periodKey].forEach(timeObj => {
        // 遍历具体的时间键值
        for (const timeProp in timeObj) {
          console.log(`    ${timeProp}: ${timeObj[timeProp]}`);
        }
      });
    }
  });
}

3. 通用递归遍历函数(支持任意嵌套深度)

如果你的JSON结构可能变化,用递归函数可以自动遍历所有层级的键值:

function traverseAllKeys(obj, prefix = '') {
  for (const key in obj) {
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      console.log(`${prefix}键: ${key}`);
      // 处理数组,标注索引
      if (Array.isArray(obj[key])) {
        obj[key].forEach((item, index) => {
          traverseAllKeys(item, `${prefix}  [${index}] `);
        });
      } else {
        traverseAllKeys(obj[key], `${prefix}  `);
      }
    } else {
      console.log(`${prefix}${key}: ${obj[key]}`);
    }
  }
}

// 调用函数遍历所有键值
traverseAllKeys(jsonData);

输出示例

执行上述代码后,会得到清晰的层级输出:

日期: Monday
  时段: morning
    start_time: 02:00
    end_time: 07:30
  时段: afternoon
    start_time: 02:00
    end_time: 05:00
  时段: evening
    start_time: 02:30
    end_time: 07:00
日期: Tuesday
  时段: morning
    start_time: 02:00
    end_time: 07:30
  时段: afternoon
    start_time: 02:00
    end_time: 05:00
  时段: evening
    start_time: 02:30
    end_time: 07:00

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:42:37