将列表(数组)转换为树形结构的函数
// tree from list
// 列表中的树
export function listToTree<T = any>(list: any[], config: Partial<TreeHelperConfig> = {}): T[] {
const conf = getConfig(config) as TreeHelperConfig;
//nodeMap 是一个 Map,用于存储每个节点的引用,以 id 为键,节点对象为值。
const nodeMap = new Map();
const result: T[] = [];
const { id, children, pid } = conf;
//遍历输入的列表 list,为每个节点初始化 children 字段(如果不存在的话)。
//将每个节点存储到 nodeMap 中,以便后续可以通过 id 快速查找父节点。
for (const node of list) {
node[children] = node[children] || [];
nodeMap.set(node[id], node);
}
//再次遍历列表,根据每个节点的 pid 在 nodeMap 中查找其父节点。
//如果找到了父节点(parent),将当前节点添加到父节点的 children 数组中。
//如果没有找到父节点(即当前节点是根节点),则将当前节点添加到 result 数组中。
for (const node of list) {
const parent = nodeMap.get(node[pid]);
(parent ? parent[children] : result).push(node);
}
return result;
}
示例使用
const list = [
{ id: 1, pid: null, name: 'Root' },
{ id: 2, pid: 1, name: 'Child 1' },
{ id: 3, pid: 1, name: 'Child 2' },
{ id: 4, pid: 2, name: 'Grandchild' }
];
调用结果
[
{
id: 1,
pid: null,
name: 'Root',
children: [
{ id: 2, pid: 1, name: 'Child 1', children: [{ id: 4, pid: 2, name: 'Grandchild', children: [] }] },
{ id: 3, pid: 1, name: 'Child 2', children: [] }
]
}
]

被折叠的 条评论
为什么被折叠?



