本帖记录一下小程序配合tdesign框架中<t-tree-select>组件开发过程中碰到的数据转换方法
额外要求是
1、得有一个全部地区 包括 市子节点以及县子节点均为全部地区
2、当为直辖市的时候,最深只有市节点,则把县节点也赋值为市节点
3、台湾、香港、澳门这种单独的存在没有市区县区分的,三个节点均一致
接口返回的数据如下如所示
代码如下:
export function buildTree(regions) {
// 筛选省份
const provinces = regions.filter(region => region.parentId === "0");
// 筛选市区以及其子项
const cities = provinces.map(province => {
const provinceId = province.id;
const provinceName = province.name;
const provinceCode = province.code;
//筛选出当前省份的下一级
const provinceCities = regions.filter(region => region.parentId === provinceId);
//对市区级别进行处理
const cityList = provinceCities.map(city => {
const cityId = city.id;
const cityName = city.name;
const cityCode = city.code;
const cityRegions = regions.filter(region => region.parentId === cityId);
if (cityRegions.length === 0) {
// 如果市区下没有子项,创建一个只包含市区自身的叶子节点对象
return {
id: cityId,
label: cityName,
value: cityCode,
children: [{
id: cityId,
label: cityName,
value: cityCode
}]
};
}
const regionList = cityRegions.map(region => {
// 将子项转换为包含ID、名称和代码的对象
return {
id: region.id,
label: region.name,
value: region.code
};
});
// 将子项列表作为市区的子节点
return {
id: cityId,
label: cityName,
value: cityCode,
children: regionList
};
});
if (cityList.length === 0) {
// 如果市区列表为空,创建一个只包含省份自身的叶子节点对象
return {
id: provinceId,
label: provinceName,
value: provinceCode,
children: [{
id: provinceId,
label: provinceName,
value: provinceCode,
children: [{
id: provinceId,
label: provinceName,
value: provinceCode
}]
}]
};
}
const hasRegions = cityList.some(city => city.children && city.children.length > 0);
if (!hasRegions) {
// 检查市区列表中是否有子项,如果没有,将每个市区的children属性设置为只包含市区自身的数组
cityList.forEach(city => {
city.children = [{
id: city.id,
label: city.label,
value: city.value
}];
});
}
// 将市区列表作为省份的子节点
return {
id: provinceId,
label: provinceName,
value: provinceCode,
children: cityList
};
});
// 根据地区编码的首字母的ASCII码降序排列
cities.sort(function (b, a) {
var x = (a['value'].substr(0, 1)).charCodeAt()
var y = (b['value'].substr(0, 1)).charCodeAt()
return y - x
});
// 创建一个名为"全部地区"的根节点
const allRegions = {
id: "all",
label: "全部地区",
value: "",
children: [{
id: "all",
label: "全部地区",
value: "",
children: [{
id: "all",
label: "全部地区",
value: ""
}]
}]
};
// 返回根节点和排序后的结果数组
return [allRegions, ...cities];
}