您的位置:首页 >热讯 >

一维数组转树状,常用菜单 栏目路由 转换成多维数组 多级菜单转换

2022-03-17 12:55:15    来源:小焱

原标题:一维数组转树状,常用菜单 栏目路由 转换成多维数组 多级菜单转换

用于将一维数组转换为树状结构,通常用于栏目菜单功能

/**

* 树状路由转换

* @param nodes 一维数组

* @param parentKey 匹配的字段

* @param childrenName 子集名称

* @param rootKeys 父类的值

* @returns 树状

*/

export function setTree(nodes: any[], parentKey = "parent_id", childrenName:"children", rootKeys: any = [0, "root"]) {

const rootNode: any[] = [];

const _child: any[] = [];

nodes.forEach((item) => {

const parentId = item[parentKey];

if (parentId == null || rootKeys.includes(parentId)) {

rootNode.push(item);

} else {

_child.push(item);

}

});

rootNode.forEach((item) => {

item[childrenName] = getChild(item.id, _child, parentKey, childrenName);

});

return rootNode;

}

/**

* 从数组中找到其父级

* @param id 父组件ID

* @param allNode 所有列表

* @param parentKey 当前组件的父级ID

* @returns 返回一个tree

*/

export function getChild(id: number, allNode: any[], parentKey: string, childrenName: string): any[] {

// 未获取到的

const _child: any[] = [];

//存放子菜单的集合

const listChild: any[] = [];

allNode.forEach((item) => {

if (item[parentKey] === id) {

listChild.push(item);

} else {

_child.push(item);

}

});

if (listChild.length) {

listChild.forEach((child) => {

child[childrenName] = getChild(child.id, _child, parentKey, childrenName);

});

}

return listChild;

}

关键词: 一维数组 多维数组

相关阅读