提交 03ac1668 编写于 作者: 水晶土豆

Wed Nov 15 18:41:00 CST 2023 inscode

上级 e8820ec6
const treeData = [
{
id: 1,
title: "课程1",
children: [
{ id: 4, title: "课程1-1" },
{
id: 5,
title: "课程1-2",
children: [
{ id: 6, 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" },
]
export function TreeToFlat(data) {
let formatData = []
for (var i = 0; i < data.length; i++) {
formatData.push({
id: data[i].id,
title: data[i].title,
})
if (data[i].children) {
formatData = formatData.concat(TreeToFlat(data[i].children));
}
}
return formatData;
}
// console.log(TreeToFlat(treeData), '输出为扁平化结构')
function FlatToTree(arr) {
const map = arr.reduce((acc, val) => {
acc[val.id] = val
return acc
}, {})
const tree = []
arr.forEach(region => {
if (region.parent) {
const parent = map[region.parent]
if (!parent.children) {
parent.children = [region]
}
else {
parent.children.push(region)
}
}
else {
tree.push(region)
}
})
return { tree }
}
// console.log(FlatToTree(flatData),'输出为树形结构')
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册