const treeData = [
{
id: 1,
title: "课程1",
children: [
{ id: 4, title: "课程1-1" },
{
id: 5,
title: "课程1-2",
children: [
{ id: 6, title: "课程1-2-1", children: [{ id: 8, title: "课程1-2-1" },] },
{ id: 7, title: "课程1-2-2" },
],
},
],
},
{ id: 2, title: "课程2" },
{ id: 3, title: "课程3" },
];
const flatData = [
{ id: 1, parent: 0, title: "课程1" },
{ id: 4, parent: 1, title: "课程1-1" },
{ id: 5, parent: 1, title: "课程1-2" },
{ id: 6, parent: 5, title: "课程1-2-1" },
{ id: 7, parent: 5, title: "课程1-2-2" },
{ id: 2, parent: 0, title: "课程2" },
{ id: 3, parent: 0, title: "课程3" },
]
function treeToflat(treeData, res = [], pid = 0) {
for (let i = 0; i < treeData.length; i++) {
res.push({
id: treeData[i].id,
title: treeData[i].title,
parent: pid
})
if (treeData[i].children) {
treeToflat(treeData[i].children, res, treeData[i].parent)
}
}
return res;
}
function flatTotree(list) {
// let tree = list[0];
let r = []
function getChildren(subList, res, parent) {
for (let i = 0; i < subList.length; i++) {
console.log(subList[i].id, parent)
if (subList[i].parent === parent) {
const newItem = { ...subList[i], children: [] };
res.push(newItem);
console.log(res)
getChildren(subList, newItem.children, subList[i].id)
}
}
}
getChildren(list, r, 0)
return r;
}
// 非递归实现
function formatTree(list) {
let obj = {}, trees = [];
list.forEach(item => {
obj[item.id] = item;
})
list.forEach(item => {
let parent = obj[item.parent];
if (parent) (parent.children || (parent.children = [])).push(item);
else trees.push(item)
})
return trees;
}
console.log(JSON.stringify(flatTotree(flatData)));
06-22
201
03-03
380
09-29
1万+
03-13
1705