- 正向-树形结构转平铺
// 正向-树形结构转平铺
// 从外到内依次递归,有 children 则继续递归
function treeToArr(data, pid=null, res=[]) {
data.forEach(item => {
res.push({ pid: pid, id: item.id, name: item.name });
if(item.children && item.children.length !== 0) {
treeToArr(item.children, item.id, res);
}
});
return res;
};
const arr = treeToArr(data);
console.log(arr);
2.逆向-平铺结构转树形
// 依次在数组中找到每一层级对应的元素,同时每个元素的 children 属性对应的 value 通过 pid 去找到,然后递归执行下去
function arrToTree(arr, pid=null) {
const res = [];
arr.forEach(item => {
if(item.pid === pid) {
// 这样每次都需要遍历整个数组,因此时间复杂度为 n*n
// const children = arrToTree(arr, item.id)
// 往下递归时,每次数组的大小都在减小,每次都筛选掉父代元素,最终的时间复杂度为 n*logn
const children = arrToTree(arr.filter(v => v.pid !== pid), item.id);
if(children.length) {
res.push({ ...item, children })
}else {
res.push({ ...item })
}
}
});
return res;
};
const tree = arrToTree(arr);
console.log(JSON.stringify(tree, null, 2));
本文介绍了如何在JavaScript中进行数据转换,特别是树形结构转化为平铺结构,以及平铺结构转化为树形结构的方法。通过递归方式,从外到内遍历并处理数据,实现两种结构的相互转换。

被折叠的 条评论
为什么被折叠?



