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 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')
标签:const,pid,list,children,itemMap,数组,转树,id
From: https://blog.51cto.com/u_15930000/7387970