将下列数组进行转换:
const list = [
{ id: 1, name: "部门1", pid: 0 },
{ id: 2, name: "部门1-1", pid: 1 },
{ id: 3, name: "部门1-2", pid: 1 },
{ id: 4, name: "部门1-1-1", pid: 2 },
{ id: 5, name: "部门1-2-1", pid: 3 },
{ id: 6, name: "部门2", pid: 0 },
{ id: 7, name: "部门2-1", pid: 6 },
{ id: 8, name: "部门3", pid: 0 },
];
期望结果:
const listTree = [
{
id: 1,
name: "部门1",
pid: 0,
children: [
{
id: 2,
name: "部门1-1",
pid: 1,
children: [
{
id: 4,
name: "部门1-1-1",
pid: 2,
children: [],
},
],
},
{
id: 3,
name: "部门1-2",
pid: 1,
children: [
{
id: 5,
name: "部门1-2-1",
pid: 3,
children: [],
},
],
},
],
},
{
id: 6,
name: "部门2",
pid: 0,
children: [
{
id: 7,
name: "部门2-1",
pid: 6,
children: [],
},
],
},
{
id: 8,
name: "部门3",
pid: 0,
children: [],
},
];
递归实现
// 递归查找获取子节点
const getChild = (list, result, pid) => {
for (const item of list) {
if (item.pid === pid) {
const newItem = { ...item, children: [] };
result.push(newItem);
getChild(list, newItem.children, item.id);
}
}
};
// 调用递归实现
const listToTree = (list, pid) => {
const result = [];
getChild(list, result, pid);
return result;
};
listToTree(list, 0);
Map对象实现
const listToTree = (list) => {
// 最终树形结构输出的结果
const result = [];
const itemMap = {};
for (const item of list) {
const id = item.id;
const pid = item.pid;
if (!itemMap[id]) {
itemMap[id] = {
children: [],
};
}
itemMap[id] = {
...item,
children: itemMap[id]["children"],
};
const treeItem = itemMap[id];
if (pid === 0) {
result.push(treeItem);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
};
}
itemMap[pid].children.push(treeItem);
}
}
return result;
};
listToTree(list, 0);
filter实现
const listToTree = (list, key) => {
const tree = list.filter(function (parent) {
// 返回每一项得的子级数据
const branchArr = list.filter((child) => parent.id === child[key]);
parent.children = [];
// 如果存在子级,则给父级添加一个children属性并赋值
if (branchArr.length > 0) {
parent.children = branchArr;
}
// 返回第一层
return parent[key] == 0;
});
return tree;
};
// 传入原始数据和父级pid的key
listToTree(list, "pid");