如下数据:
[
{
"id": 1,
"name": "11111111楼",
"parentId": 0
},
{
"id": 2,
"name": "2楼",
"parentId": 0
},
{
"id": 4,
"name": "1楼儿子2",
"parentId": 1
},
{
"id": 6,
"name": "你是谁啊",
"parentId": 4
},
{
"id": 12,
"name": "566666",
"parentId": 2
},
{
"id": 13,
"name": "33333楼",
"parentId": 0
},
{
"id": 14,
"name": "7567566765",
"parentId": 13
},
{
"id": 15,
"name": "1312",
"parentId": 6
}
]
生成树结构代码:
load() {
loadCatOptions().then(res => {//发送请求获取数据
this.catOptions = this.generateOptions(res);
console.log(this.catOptions);
})
},
generateOptions(params) {//生成Cascader级联数据
var result = [];
for (let param of params) {
if (param.parentId == 0) {//判断是否为顶层节点
var parent = {//转换成el-Cascader可以识别的数据结构
'label': param.name,
'value': param.id
}
parent.children = this.getchilds(param.id, params);//获取子节点
result.push(parent);
}
}
return result;
},
getchilds(id, array) {
let childs = new Array();
for (let arr of array) {//循环获取子节点
if (arr.parentId == id) {
childs.push({
'label': arr.name,
'value': arr.id
});
}
}
for (let child of childs) {//获取子节点的子节点
let childscopy = this.getchilds(child.value, array);//递归获取子节点
console.log(childscopy)
if (childscopy.length > 0) {
child.children = childscopy;
}
}
return childs;
},
转换后的数据:
[
{
"children": [
{
"children": [
{
"children": [
{
"label": "1312",
"value": 15
}
],
"label": "你是谁啊",
"value": 6
}
],
"label": "1楼儿子2",
"value": 4
}
],
"label": "11111111楼",
"value": 1
},
{
"children": [
{
"label": "566666",
"value": 12
}
],
"label": "2楼",
"value": 2
},
{
"children": [
{
"label": "7567566765",
"value": 14
}
],
"label": "33333楼",
"value": 13
}
]
根据树形数据生成树形文档
function g(count, title) {
return (
Array(count - 1)
.fill("----")
.join("") + title
);
}
let txt = "";
function loop(menus, count) {
count++;
for (const item of menus) {
item.count = count;
txt += g(item.count, item.title) + '----' + item.key + "\n";
loop(item.children || [], item.count);
}
}
loop(menu, 0);
fs.writeFileSync("./1.txt", txt);