递归和非递归两种方式
非递归方法:
优点:数据比较多的时候也可以使用,性能比递归方式快很多
缺点:代码较多些,没递归方式易懂
var arr = [
{ id: 1, pid: 0 },
{ id: 2, pid: 1 },
{ id: 4, pid: 1 },
{ id: 5, pid: 2 },
{ id: 6, pid: 2 },
{ id: 7, pid: 4 },
{ id: 8, pid: 0}
];
// 列表转树 不使用递归方式
function list2tree(list) {
const arr = [];
list.forEach((v) => {
const newList = list.filter((k) => k.id !== v.id);
// 如果没有找到这一项的父元素那么可以确定它是根元素
// find 表示查找 找到了返回那一项 找不到返回undefined
const root = newList.find((t) => t.id === v.pid);
if (!root) {
// 往数组中追加根元素
arr.push(v);
}
// 找当前项的子元素
const children = newList.filter((k) => k.pid === v.id);
// 找到了就赋值
if (children.length) {
v.children = children;
} else {
v.children = [];
}
});
return arr;
}
console.log(to(arr));
递归方法:
将列表型的数据转化成树形数据 => 递归算法 => 自身调用自身 => 一定条件不能一样, 否则就会死循环
优点:代码简洁,通俗易懂
缺点:只能少量递归数据时使用,太多数据教消耗性能
function transListToTreeData(list, rootValue) {
var arr = []
list.forEach(item => {
if (item.pid === rootValue) {
// 找到之后 就要去找item下面有没有子节点
const children = transListToTreeData(list, item.id)
if (children.length) {
// 如果children的长度大于0 说明找到了子节点
item.children = children
}
arr.push(item) // 将内容加入到数组中
}
})
return arr
}