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

Flutter/Dart如何从嵌套Map中提取postal_code字段值

问题:从嵌套Map中提取postal_code对应的数值52034

给定的嵌套Map结构如下:

{
  plus_code: {
    compound_code: "QW8C+JTA ExampleTown, ExampleCountry",
    global_code: "8FFGDSC+JTA"
  }, 
  results: [
    {
      address_components: [
        {long_name: "31", short_name: "31", types: ["street_number"]}, 
        {long_name: "ExampleRoute", short_name: "ExampleRoute", types: ["route"]}, 
        {long_name: "ExampleTown", short_name: "ExampleTown", types: ["locality", "political"]}, 
        {long_name: "ExampleCountry", short_name: "DE", types: ["country", "political"]}, 
        {long_name: "52034", short_name: "52034", types: ["postal_code"]}
      ], 
      formatted_address: "ExampleRoute 31, 52034 ExampleTown, ExampleCountry", 
      geometry: {location: {lat: 12.345678, lng: 12.345678}}
    }
  ]
}

当前尝试的代码片段:

print(data["results"][0]["address_components"]...???..);

需要补充完整代码以获取postal_code对应的数值52034。


解决方案

要获取目标邮编,你需要遍历address_components数组,筛选出types包含postal_code的对象,再提取对应的字段值。

ES6+ 简洁实现

// 找到包含postal_code的地址组件
const postalCodeEntry = data.results[0].address_components.find(comp => 
  comp.types.includes('postal_code')
);

// 提取邮编值(long_name和short_name值一致,任选其一)
const postalCode = postalCodeEntry?.long_name;

print(postalCode); // 输出:52034

兼容旧环境的实现

如果运行环境不支持ES6语法,可使用循环遍历:

let postalCode = '';
const components = data.results[0].address_components;

for (let i = 0; i < components.length; i++) {
  if (components[i].types.indexOf('postal_code') !== -1) {
    postalCode = components[i].long_name;
    break; // 找到后跳出循环,提升效率
  }
}

print(postalCode); // 输出:52034

关键说明

  • find()方法会返回第一个匹配条件的数组元素,适合这种场景下的精准筛选
  • 可选链?.用于防止找不到匹配元素时抛出Cannot read properties of undefined错误
  • 目标对象的long_name和short_name均为52034,根据需求选择其中一个即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:45:29