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

Dart中如何按ID列表遍历树形Map并实现动态赋值?

问题描述

应用中有一个按钮用于修改工单的meeting_type,工单关联location_id,部分location_id存在树形层级(子父级关系)。已获取完整ID列表,列表首个ID是最深层级子节点,最后一个是根父节点。需要循环检查ID列表对应的树形Map结构:

  • 若当前层级存在对应键则继续深入
  • 若不存在则终止循环,将剩余ID对应的键值设为空对象

树形Map结构示例

tempData: {
  "location-id-a": {
    "location-id-b": {
      "location-id-c": {
        "ticket_list": ["ticket_id_a", "ticket_id_b", "ticket_id_c"],
        "location-id-d": {}
      }
    }
  }
}

现有实现代码

for (int i = locationList.length - 1; i >= 0; i--) {
    String key = locationList[i];

    if (i == 0) {
      if (tempData[key].containsKey('temuan_list')) {
        List<String> temuanList = List.from(tempData[key]['temuan_list']);
        if(!temuanList.contains(temuanId)){
          temuanList.add(temuanId);
        }
        tempData[key]['temuan_list'] = temuanList;
      } else {
        tempData[key]['temuan_list'] = [temuanId];
      }
    } else {
      /// 检查当前键是否存在,存在则深入
      if (tempData.containsKey(key)) {
        tempData = tempData[key];
      } else {
        /// 问题所在:无法动态维护嵌套结构,硬编码索引不通用
        tempData[locationList[2]][locationList[1]][locationList[0]] = {};
        break;
      }
    }
  }

当前代码无法动态处理任意深度的嵌套结构,硬编码索引仅适用于特定长度的ID列表,需优化实现。


解决方案

核心思路是用临时指针跟踪当前层级的Map,而非直接修改原tempData,既能保留外层结构,又能动态创建缺失的嵌套节点。具体实现如下:

// 保留原tempData引用,用currentMap跟踪当前操作层级
var currentMap = tempData;
bool hasMissingKey = false;

for (int i = locationList.length - 1; i >= 0; i--) {
  String key = locationList[i];
  
  if (hasMissingKey) {
    // 已遇到缺失键,继续创建后续层级的空Map
    currentMap[key] = {};
    currentMap = currentMap[key];
    continue;
  }

  if (i == 0) {
    // 处理最深层级的temuan_list逻辑
    if (currentMap.containsKey(key)) {
      var targetMap = currentMap[key];
      if (targetMap.containsKey('temuan_list')) {
        List<String> temuanList = List.from(targetMap['temuan_list']);
        if (!temuanList.contains(temuanId)) {
          temuanList.add(temuanId);
        }
        targetMap['temuan_list'] = temuanList;
      } else {
        targetMap['temuan_list'] = [temuanId];
      }
    } else {
      // 若最深层级键不存在,直接创建并初始化temuan_list
      currentMap[key] = {
        'temuan_list': [temuanId]
      };
    }
  } else {
    if (currentMap.containsKey(key)) {
      // 键存在,深入到子Map层级
      currentMap = currentMap[key];
    } else {
      // 键不存在,创建当前键的空Map并标记后续需自动创建
      currentMap[key] = {};
      currentMap = currentMap[key];
      hasMissingKey = true;
    }
  }
}

关键改进点

  • 使用currentMap指针跟踪当前操作层级,避免修改原tempData引用导致外层结构丢失
  • 通过hasMissingKey标记,遇到缺失键后自动创建剩余所有层级的空Map,适配任意长度的locationList
  • 补充了最深层级键不存在时的处理逻辑,确保结构完整性
  • 移除硬编码索引,实现动态嵌套结构维护

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 00:47:17