官方数据示例
const areaList = {
province_list: {
110000: "北京市",
120000: "天津市",
},
city_list: {
110100: "北京市",
120100: "天津市",
},
county_list: {
110101: "东城区",
110102: "西城区",
110105: "朝阳区",
110106: "丰台区",
110107: "石景山区",
110108: "海淀区",
110109: "门头沟区",
110111: "房山区",
110112: "通州区",
110113: "顺义区",
110114: "昌平区",
110115: "大兴区",
110116: "怀柔区",
110117: "平谷区",
110118: "密云区",
110119: "延庆区",
120101: "和平区",
120102: "河东区",
120103: "河西区",
120104: "南开区",
120105: "河北区",
120106: "红桥区",
120110: "东丽区",
120111: "西青区",
120112: "津南区",
120113: "北辰区",
120114: "武清区",
120115: "宝坻区",
120116: "滨海新区",
120117: "宁河区",
120118: "静海区",
120119: "蓟州区",
},
};
处理数据代码
function convertCityDataToTree(data) {
const { province_list, city_list, county_list } = data;
const treeData = [];
// 遍历省份列表
for (const provinceCode in province_list) {
const provinceName = province_list[provinceCode];
const provinceNode = {
Code: provinceCode,
Name: provinceName,
ChildList: [],
};
// 遍历城市列表
for (const cityCode in city_list) {
if (cityCode.startsWith(provinceCode.substring(0, 2))) {
const cityName = city_list[cityCode];
const cityNode = { Code: cityCode, Name: cityName, ChildList: [] };
// 遍历区县列表
for (const countyCode in county_list) {
if (countyCode.startsWith(cityCode.substring(0, 4))) {
const countyName = county_list[countyCode];
const countyNode = { Code: countyCode, Name: countyName };
cityNode.ChildList.push(countyNode);
}
}
provinceNode.ChildList.push(cityNode);
}
}
treeData.push(provinceNode);
}
return treeData;
}
// 调用函数进行转换
const treeCityData = convertCityDataToTree(areaList);
console.log(treeCityData);