const routes = [
{
name: "首页",
type: 0,
children: [],
},
{
name: "系统管理",
type: 0,
children: [
{
name: "用户管理",
type: 0,
children: [
{
name: "新建用户",
type: 1,
children: [],
},
],
},
{
name: "角色管理",
type: 0,
children: [
{
name: "新建角色",
type: 1,
children: [],
},
{
name: "成员管理",
type: 1,
children: [],
},
],
},
],
},
];
[
{
name: "首页",
type: 0,
children: [],
},
{
name: "系统管理",
type: 0,
children: [
{
name: "用户管理",
type: 0,
children: [],
},
{
name: "新建用户",
type: 1,
children: [],
},
{
name: "角色管理",
type: 0,
children: [],
},
{
name: "新建角色",
type: 1,
children: [],
},
{
name: "成员管理",
type: 1,
children: [],
},
],
},
];
遍历一下json,把type=1的挑出来,形成新的json数组
for (let i = 0, j = routes.length; i < j; i++) {
if (routes[i].children.length > 0) {
recursionFcn(routes[i].children, routes, i)
}
}
/**
* recursionFcn 递归跑type为1的子项
* @param {Array} optObj 当前操作项
* @param {Array} grandfatherTarget 祖父数组
* @param {Number} fatherIdx 当前操作在父项中的位置
* 待优化:没排序,要排序就把传递的fatherIdx换为name值,然后每次在父节点findindex当前name的位置
* **/
function recursionFcn(optObj, grandfatherTarget, fatherIdx) {
for (let i = 0; i < optObj.length; i++) {
if (optObj[i].type == 1&&optObj[i].moved!='yes') {
let movedObj= optObj[i];//被移动的节点
movedObj.moved='yes'
grandfatherTarget.splice(fatherIdx, 0, ...optObj.splice(i, 1));//这里可优化
if (movedObj?.children?.length > 0) {//被移动后,就和父级一个层级,所以把原先的祖父节点直接丢就可以了
recursionFcn(movedObj.children, grandfatherTarget, fatherIdx);
}
i--;//移动后,之前为0的i就会定位到1上,所以回退,在for i++里会重新加回来的
}
else {
//没移动
if (optObj[i]?.children?.length > 0) {
recursionFcn(optObj[i].children, optObj, i);
}
}
}
}