如下數據:
[
{
"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);