1、数组转树结构
const data = [
{ id: "01", lable: "项目经理", pid: "" },
{ id: "02", lable: "产品leader", pid: "01" },
{ id: "03", lable: "UIleader", pid: "01" },
{ id: "04", lable: "技术leader", pid: "01" },
{ id: "05", lable: "测试leader", pid: "01" },
{ id: "06", lable: "运维leader", pid: "01" },
{ id: "07", lable: "产品经理", pid: "02" },
{ id: "08", lable: "产品经理", pid: "02" },
{ id: "09", lable: "UI设计师", pid: "03" },
{ id: "10", lable: "前端工程师", pid: "04" },
{ id: "11", lable: "后端工程师", pid: "04" },
{ id: "12", lable: "后端工程师", pid: "04" },
{ id: "13", lable: "测试工程师", pid: "05" },
{ id: "14", lable: "测试工程师", pid: "05" },
{ id: "15", lable: "运维工程师", pid: "06" },
];
let d = dataTotree(data)
console.log(d)
function dataTotree(data) {
let tree = [];
const obj = {};
data.forEach((v) => {
v.children = [];
obj[v.id] = v;
});
data.forEach((v) => {
if (v.pid) {
obj[v.pid].children.push(v)
} else {
tree.push(v)
}
})
return tree
}
2、树结构转数组
let node = {
"id": 0,
"parentId": null,
"name": "生物",
"children": [{
"id": 1,
"parentId": 0,
"name": "动物",
"children": [{
"id": 4,
"parentId": 1,
"name": "哺乳动物",
"children": [{
"id": 8,
"parentId": 4,
"name": "大象"
}, {
"id": 9,
"parentId": 4,
"name": "海豚"
}, {
"id": 10,
"parentId": 4,
"name": "猩猩"
}]
}, {
"id": 5,
"parentId": 1,
"name": "卵生动物",
"children": [{
"id": 11,
"parentId": 5,
"name": "蟒蛇"
}, {
"id": 12,
"parentId": 5,
"name": "麻雀"
}]
}]
}, {
"id": 2,
"parentId": 0,
"name": "植物",
"children": [{
"id": 6,
"parentId": 2,
"name": "种子植物"
}, {
"id": 7,
"parentId": 2,
"name": "蕨类植物"
}]
}, {
"id": 3,
"parentId": 0,
"name": "微生物"
}]
}
console.log(treeToarr(node))
function treeToarr(node) {
let queue = [node]
let data = []
while(queue.length !== 0) {
let item = queue.shift()
data.push({
id: item.id,
name: item.name,
parentId: item.parentId
})
let children = item.children
if(children) {
children.forEach(v => {
queue.push(v)
})
}
}
return data
}