1,测试数据 转换前
let list = [
{
college: "梦想的学院",
grade: "一年级",
clazz: "1班",
},
{
college: "嗷嗷叫学院",
grade: "二年级",
clazz: "1班",
id: "xxx",
},
{
college: "嗷嗷叫学院",
grade: "一年级",
clazz: "1班",
id: "biubiubiu",
},
{
college: "慢羊羊村大学",
grade: "一年级",
clazz: "1班",
},
{
college: "梦想的学院",
grade: "二年级",
clazz: "1班",
},
{
college: "慢羊羊村大学",
grade: "一年级",
clazz: "1班",
},
];
2,转换后的树形结构
[
{
title: "梦想的学院",
children: [
{
title: "一年级",
children: [
{
title: "1班",
children: [
{ college: "梦想的学院", grade: "一年级", clazz: "1班" },
],
},
],
},
{
title: "二年级",
children: [
{
title: "1班",
children: [
{ college: "梦想的学院", grade: "二年级", clazz: "1班" },
],
},
],
},
],
},
{
title: "嗷嗷叫学院",
children: [
{
title: "二年级",
children: [
{
title: "1班",
children: [
{
college: "嗷嗷叫学院",
grade: "二年级",
clazz: "1班",
id: "xxx",
},
],
},
],
},
{
title: "一年级",
children: [
{
title: "1班",
children: [
{
college: "嗷嗷叫学院",
grade: "一年级",
clazz: "1班",
id: "biubiubiu",
},
],
},
],
},
],
},
{
title: "慢羊羊村大学",
children: [
{
title: "一年级",
children: [
{
title: "1班",
children: [
{ college: "慢羊羊村大学", grade: "一年级", clazz: "1班" },
{ college: "慢羊羊村大学", grade: "一年级", clazz: "1班" },
],
},
],
},
],
},
];
3、使用递归实现
递归实现的代码
// 形成条件
const winCondition = ["college", "grade", "clazz"];
// 函数
function data2TreeDigui(list, condition) {
const newArr = [];
condition = JSON.parse(JSON.stringify(condition));
let order = condition.shift();
let holdArr = [];
const deep = condition.length;
list.forEach((item, index) => {
const holdIndex = holdArr.indexOf(item[order]);
if (holdIndex > -1) {
newArr[holdIndex]["children"].push(item);
newArr[holdIndex]["title"] = item[order];
} else {
holdArr.push(item[order]);
newArr.push({
title: item[order],
children: new Array(item),
});
}
});
newArr.forEach((item, index) => {
if (item.children.length > 0 && deep) {
// 给children赋值 递归
item.children = data2TreeDigui(item.children, condition);
}
});
return newArr;
}
// 结果
const treeData = data2TreeDigui(list, winCondition);
console.log("treeData: ", JSON.stringify(treeData));
07-08
817

08-25
370

12-03
1002

12-06
555
