const arr = [ { id: 1, parent: null, name: "根节点1" }, { id: 2, parent: 1, name: "子节点1" }, { id: 3, parent: 1, name: "子节点2" }, { id: 4, parent: 2, name: "孙节点1" }, { id: 5, parent: 2, name: "孙节点2" },];
function arrayToTree(arr) {
const map = new Map();
for (const item of arr) {
map.set(item.id, item);
}
const roots = [];
for (const item of arr) {
if (item.parent === null) {
roots.push(item);
} else {
const parent = map.get(item.parent);
if (!parent.children) {
parent.children = [];
}
parent.children.push(item);
}
}
return roots;
}
console.log(arrayToTree(arr));