// label 区域名称
// level 等级0代表省级 1代表市区 2代表县级
// PId 父级的code
// code 当前code
list1: [
{ label: "浙江省", level: 0, PId: 0, code: 330000 },
{ label: "杭州市", level: 1, PId: 330000, code: 330100 },
{ label: "宁波市", level: 1, PId: 330000, code: 330200 },
{ label: "温州市", level: 1, PId: 330000, code: 330300 },
{ label: "嘉兴市", level: 1, PId: 330000, code: 330400 },
{ label: "湖州市", level: 1, PId: 330000, code: 330500 },
{ label: "上城区", level: 2, PId: 330100, code: 330102 },
{ label: "下城区", level: 2, PId: 330100, code: 330103 },
{ label: "江干区", level: 2, PId: 330100, code: 330104 },
{ label: "河南省", level: 0, PId: 0, code: 410000 },
{ label: "郑州市", level: 1, PId: 410000, code: 410100 },
{ label: "开封市", level: 1, PId: 410000, code: 410200 },
{ label: "陕西省", level: 0, PId: 0, code: 715200 },
{ label: "西安市", level: 1, PId: 715200, code: 715201 },
{ label: "咸阳市", level: 1, PId: 715200, code: 715202 },
{ label: "宝鸡市", level: 1, PId: 715200, code: 715203 },
{ label: "铜川市", level: 1, PId: 715200, code: 715204 },
{ label: "渭南市", level: 1, PId: 715200, code: 715205 },
{ label: "延安市", level: 1, PId: 715200, code: 715206 },
{ label: "澄城县", level: 2, PId: 715205, code: 715250 },
{ label: "富平县", level: 2, PId: 715205, code: 715250 },
{ label: "蒲城县", level: 2, PId: 715205, code: 715250 },
],
mounted() {
let data = this.listToTree(this.list1);
let data1 = this.treeToList(data);
window.console.log(data, "skkccccccccc", data1);
},
methods: {
// 将扁平化数据处理为树形数据
// 当前的PId等于父级的code
listToTree(data) {
return data.filter((parentItem) => {
// 每一级的数据filterD
const filterD = data.filter((item) => {
return parentItem.code === item.PId;
});
//
// 取filterD长度大于0 的
filterD.length > 0 ? (parentItem.children = filterD) : "";
// 只取PId为0的,也就是最顶层
return parentItem.PId === 0;
});
},
// 将树形数据处理为扁平化数据(多级) 用递归
treeToList(data) {
var list = [];
const funChild = (childData) => {
childData.forEach((element) => {
element.children && element.children.length > 0
? funChild(element.children)
: ""; //子级递归
delete element.children;//删除children 根据需求看是否需要删除
list.push(element);
});
};
funChild(data);
window.console.log(data, list);
return list;
},
}
|