原有的树结构
const jsdata = [
{
category: 1,
name: '第一部分 常识判断',
qcount: 10,
judgeFlag: 0,
description: '常识判断开始',
children: [
{
category: 6,
name: '1.1 部分名称',
qcount: 10,
judgeFlag: 0,
description: null,
children: [
{ category: 7, name: '1.1.1 部分名称', qcount: 5, judgeFlag: 0, description: null, children: null, level: 0 },
{ category: 8, name: '1.1.2 部分名称', qcount: 5, judgeFlag: 0, description: '1.1.2头部说明', children: null, level: 0 },
],
level: 0,
},
],
level: 0,
},
{ category: 2, name: '第二部分 言语理解与表达', qcount: 5, judgeFlag: 0, description: null, children: null, level: 0 },
{
category: 3,
name: '第三部分 数量关系',
qcount: 10,
judgeFlag: 0,
description: null,
children: [
{
category: 9,
name: '3.1 部分名称',
qcount: 5,
judgeFlag: 0,
description: '3.1头部说明',
children: [{ category: 11, name: '3.1.1 部分名称', qcount: 5, judgeFlag: 1, description: null, children: null, level: 0 }],
level: 0,
},
{
category: 10, name: '3.2 部分名称', qcount: 5, judgeFlag: 0, description: null,
children: [
{ category: 7, name: '1.1.1 部分名称', qcount: 5, judgeFlag: 0, description: null, children: null, level: 0 },
{ category: 8, name: '1.1.2 部分名称', qcount: 5, judgeFlag: 0, description: '1.1.2头部说明', children: null, level: 0 },
],
level: 0
},
],
level: 0,
},
{ category: 4, name: '第四部分 判断推理', qcount: 0, judgeFlag: 0, description: null, children: null, level: 0 },
{ category: 5, name: '第五部分 资料分析', qcount: 0, judgeFlag: 0, description: null, children: null, level: 0 },
{ category: 12, name: '六、 部分名称', qcount: 0, judgeFlag: 0, description: null, children: null, level: 0 },
{ category: 13, name: '七、 部分名称', qcount: 0, judgeFlag: 0, description: null, children: null, level: 0 },
]
转换后的结构
![](https://img2020.cnblogs.com/blog/1258737/202111/1258737-20211109112602299-1292900214.png)
function combineModulePages(moduleTrees) {
let pageList = [];
let stack = [];
const fun = (arr, level = 1) => {
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (item.children && item.children.length > 0) {
stack.push({
name: item.name,
qcount: item.qcount,
category: item.category,
level,
})
fun(item.children, level + 1)
} else {
pageList.push({
qcount: item.qcount,
modules: stack.concat({
name: item.name,
qcount: item.qcount,
category: item.category,
level,
}),
level: level
})
stack = []
}
}
return pageList
}
return fun(moduleTrees)
}
console.log(combineModulePages(jsdata))