由图所知道,catalogParentId为null代表是第一级,如果catalogParentId和sid一样说明是他的子集
firstTreeData.value = buildTree(res.body);
const buildTree = (replies) => {
const tree = [];
const map = {};
// 初始化map,用于快速查找每个回复
replies.forEach(reply => {
map[reply.sid] = { ...reply, children: [] };
});
// 构建树形结构
replies.forEach(reply => {
const parent = map[reply.catalogParentId];
if (parent) {
// 如果reply有parent,则将其添加到parent的children中
parent.children.push(map[reply.sid]);
} else {
// 如果没有parent(即parent为0),则将其添加到树的根级别
tree.push(map[reply.sid]);
}
});
return tree;
}