龙空技术网

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

小焱2018 212

前言:

此时兄弟们对“treeset转数组”大约比较重视,你们都想要分析一些“treeset转数组”的相关资讯。那么小编也在网摘上汇集了一些有关“treeset转数组””的相关内容,希望大家能喜欢,朋友们快快来了解一下吧!

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

/** * 树状路由转换 * @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;}

标签: #treeset转数组