let arr = [
{ id: 1, name: "部门1", pid: 0 },
{ id: 2, name: "部门2", pid: 1 },
{ id: 3, name: "部门3", pid: 1 },
{ id: 4, name: "部门4", pid: 3 },
{ id: 5, name: "部门5", pid: 4 },
];
let result = [];
function arrayToTree1(items) {
const result = [];
const itemMap = {};
for (const item of items) {
itemMap[item.id] = { ...item, children: [] };
}
for (const item of items) {
const id = item.id;
const pid = item.pid;
const treeItem = itemMap[id];
if (pid === 0) {
result.push(treeItem);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
};
}
itemMap[pid].children.push(treeItem);
}
}
return result;
}
result = arrayToTree1(arr);
// console.log(result);
console.log(JSON.stringify(result));
console.log("========");
function arrayToTree2(items) {
const result = [];
const itemMap = new Map();
let pid0id;
items.map((item, index) => {
itemMap.set(item.id, { ...item, children: [] });
});
items.map((item, index) => {
const id = item.id;
const pid = item.pid;
const treeItem = itemMap.get(id);
if (pid === 0) {
result.push(treeItem);
} else {
if (!itemMap.get(pid)) {
itemMap.set(pid, { children: [] });
}
const _item = itemMap.get(pid);
_item.children.push(treeItem);
}
});
return result;
}
// result = arrayToTree2(arr);
// console.log(result);
// console.log(JSON.stringify(result));
function arrayToTree3(arr) {
const itemMap = {};
for (const item of arr) {
item.children = [];
itemMap[item.id] = item;
}
// 将对象添加至父节点
for (const item of arr) {
const parent = itemMap[item.pid];
if (parent) {
parent.children.push(item);
}
}
const result = arr.filter((item) => item.pid == 0);
console.log(JSON.stringify(result));
return result;
}
result = arrayToTree3(arr);
console