function arrayToTree(items, rootParentId = null) {
const nodeMap = new Map();
const roots = [];
for (const item of items) {
nodeMap.set(item.id, { ...item, children: [] });
}
for (const item of items) {
const node = nodeMap.get(item.id);
if (item.parentId === rootParentId) {
roots.push(node);
continue;
}
const parent = nodeMap.get(item.parentId);
if (parent) parent.children.push(node);
else roots.push(node); // 也可以根据业务改为抛错
}
return roots;
}