数组转树
const arr = [
{
id: 1,
pid: null,
name: "研发部",
},
{
id: 2,
pid: null,
name: "管理部",
},
{
id: 3,
pid: 1,
name: "前端研发部",
},
{
id: 4,
pid: 1,
name: "后端研发部",
},
{
id: 5,
pid: 2,
name: "行政管理部",
},
{
id: 6,
pid: 2,
name: "财务部",
},
{
id: 7,
pid: null,
name: "财务部11",
},
];
const treeDaltLis = (data, pid = null) => {
// 遍历data,返回满足pid等于传入参数的元素
return data.reduce((prev, curent) => {
// 如果curent的pid等于传入参数
if (curent.pid === pid) {
// 递归调用,传入data和curent的id
const children = treeDaltLis(data, curent.id);
// 如果children不为空
if (children.length) {
// 将curent的children属性设置为children
curent.children = children;
}
// 将curent添加到prev数组中
prev.push(curent);
}
// 返回prev
return prev;
}, []);
};
//调用方法传入数据
const tree = treeDaltLis(arr);
//打印结果
console.log(tree, "树");
打印结果如下:
树转数组
const TmpData = [
{
id: 1,
name: "部门1",
pid: 0,
children: [
{
id: 2,
name: "部门2",
pid: 1,
children: [],
},
{
id: 3,
name: "部门3",
pid: 1,
children: [],
},
],
},
{
id: 4,
name: "部门3",
pid: 0,
children: [
{
id: 5,
name: "部门4",
pid: 4,
children: [],
},
],
},
{
id: 6,
name: "部门5",
pid: 0,
children: [
{
id: 7,
name: "部门5",
pid: 6,
children: [
{
id: 8,
name: "部门5",
pid: 7,
children: [],
},
],
},
],
},
];
//调用方法传入数据
const treeToArray = (data) => {
// 遍历data,将数据转换为数组
return data.reduce((prev, curent) => {
// 如果当前节点没有子节点,则直接将当前节点添加到数组中
if (!curent.children) {
prev.push(curent);
} else {
// 如果有子节点,则递归调用treeToArray函数,将子节点转换为数组,并将当前节点和子节点数组合并
const list = treeToArray(curent.children);
// 删除当前节点的children属性,否则会递归调用
delete curent.children;
prev.push(curent, ...list);
}
// 返回合并后的数组
return prev;
}, []);
};
const arrList = treeToArray(TmpData);
console.log(arrList, "数组");
打印结果如下: