js 递归获取省市县的数据?

作者站长头像
站长
· 阅读数 7

后台返回如下接口

[
  {
    "cityAndPrefecture": [
      {
        "city": "滨海新区",
        "prefecture": []
      }
    ],
    "province": "天津市"
  },
  {
    "cityAndPrefecture": [
      {
        "city": "东营",
        "prefecture": []
      },
      {
        "city": "威海",
        "prefecture": []
      },
      {
        "city": "日照",
        "prefecture": []
      },
      {
        "city": "滨州",
        "prefecture": []
      },
      {
        "city": "潍坊",
        "prefecture": []
      },
      {
        "city": "烟台",
        "prefecture": []
      },
      {
        "city": "青岛",
        "prefecture": []
      }
    ],
    "province": "山东省"
  },
  {
    "cityAndPrefecture": [
      {
        "city": "唐山",
        "prefecture": []
      },
      {
        "city": "沧州",
        "prefecture": []
      },
      {
        "city": "秦皇岛",
        "prefecture": []
      }
    ],
    "province": "河北省"
  },
  {
    "cityAndPrefecture": [
      {
        "city": "丹东",
        "prefecture": []
      },
      {
        "city": "大连",
        "prefecture": []
      },
      {
        "city": "盘锦",
        "prefecture": []
      },
      {
        "city": "营口",
        "prefecture": []
      },
      {
        "city": "葫芦岛",
        "prefecture": []
      },
      {
        "city": "锦州",
        "prefecture": []
      }
    ],
    "province": "辽宁省"
  }
]

有没有什么简单的方法 可以实现 从返回的数据中提取省[]数组 市[]数组 县[]数组 索引对应就行 做一个三级联动 prefecture是县级市 有的会有返回

市的要求是[[省1的市],[省2的市]]同样县区 要求是 [[市1的县],[市2的县]]

回复
1个回答
avatar
test
2024-07-03
let data = [ /* 你的数据 */ ];

let provinces = data.map(item => item.province);

let cities = data.map(item => item.cityAndPrefecture.map(cityItem => cityItem.city));

let prefectures = data.map(item => item.cityAndPrefecture.map(cityItem => cityItem.prefecture));

console.log(provinces); // 省
console.log(cities); // 市
console.log(prefectures); // 县

整合:

let result = data.reduce((acc, item) => {
  acc.provinces.push(item.province);
  acc.cities.push(item.cityAndPrefecture.map(cityItem => cityItem.city));
  acc.prefectures.push(item.cityAndPrefecture.map(cityItem => cityItem.prefecture));
  return acc;
}, { provinces: [], cities: [], prefectures: [] });
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容