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

如何通过指定键列表遍历嵌套Map并检查count属性?

解决嵌套Map层级遍历问题

你的问题出在每次只检查顶层Map是否包含当前key,但实际这些key是嵌套层级的(比如location-id-b在location-id-a的子Map里,并非顶层结构),所以循环无法深入到深层。

修复思路

需要逐层递进遍历:维护一个当前层级的Map变量,每一步用当前key去当前Map中查找,找到后就将当前Map更新为该key对应的子Map,继续处理下一个key;如果中途找不到某个key,就终止流程。最后在最终的层级里检查是否存在count属性。

代码实现

Map<String, dynamic> currentMap = locationCountData;
bool allKeysExist = true;

for (String key in locationList) {
  print('当前key: $key');
  if (currentMap.containsKey(key)) {
    print('找到key $key,进入下一层级');
    // 更新当前Map为子层级的Map
    currentMap = currentMap[key] as Map<String, dynamic>;
  } else {
    print('key $key 不存在');
    allKeysExist = false;
    break;
  }
}

// 遍历完所有key后,检查当前层级是否有count属性
if (allKeysExist) {
  if (currentMap.containsKey('count')) {
    print('找到count属性,值为: ${currentMap['count']}');
  } else {
    print('最终层级没有count属性');
  }
}

代码说明

  • 初始化currentMap为顶层的locationCountData,用来跟踪当前遍历到的层级。
  • 遍历locationList中的每个key,每次在currentMap中查找:
    • 找到则更新currentMap为子Map,进入下一层;
    • 找不到则标记allKeysExist为false并终止循环。
  • 遍历完成后,若所有key都存在,就检查当前层级的Map是否包含count属性。

用你提供的数据结构测试,这段代码会依次找到location-id-a→location-id-b→location-id-c,最后检测到count:10并输出对应结果。

内容的提问来源于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:40:04