数据结构
//树结构
node = {
id: number, // 数值 parentId: number, // 数值
name: string, children: [] || null, // 用数组的方式保存子节点,适合更多业务场景
}
//线性结构
list = [
{ id: number, parentId: number, name: string },
{ id: number, parentId: number, name: string },
];
root = null || {
id: 0,
parentId: null,
children: [node1, node2, ...],
}
线性结构数组转树形结构
function listConvertTree(list) {
let root = null;
if (list && list.length) {
root = { id: 0, parentId: null, children: [] };
const group = {};
for (let index = 0; index < list.length; index += 1) {
if (list[index].parentId !== null && list[index].parentId !== undefined) {
if (!group[list[index].parentId]) {
group[list[index].parentId] = [];
}
group[list[index].parentId].push(list[index]);
}
}
const queue = [];
queue.push(root);
while (queue.length) {
const node = queue.shift();
node.children = group[node.id] && group[node.id].length ? group[node.id] : null;
if (node.children) {
queue.push(...node.children);
}
}
}
return root;
}
树形结构转线性结构数组
function treeConvertList(root) {
const list = [];
if (root) {
const Root = JSON.parse(JSON.stringify(root));
const queue = [];
queue.push(Root);
while (queue.length) {
const node = queue.shift();
if (node.children && node.children.length) {
queue.push(...node.children);
}
delete node.children;
if (node.parentId !== null && node.parentId !== undefined) {
list.push(node);
}
}
}
return list;
}