1、将树结构展平成数组对象
// 获取平铺结构 const tile = (data: any) => { let arr: any = []; for (let i = 0, l = data.length; i < l; i++) { arr.push(data[i]); if (data[i].childMenuList && data[i].childMenuList.length > 0) { arr = arr.concat(tile(data[i].childMenuList)); } } return arr; };
2、将数组对象生成树结构
// 根据平铺结构生成树结构 const genTreeData = (originData: any) => { const rootNode = originData.filter((n: any) => n.parId === 0); const genChildren = (parents: any) => { const tempParents = parents.map((parent: any) => { const children = originData.filter((m: any) => m.parId === parent.id); const tempParent = { ...parent, key: parent.id, title: parent.menuName, }; if (children.length > 0) { tempParent.children = genChildren(children); } return tempParent; }); return tempParents; }; const tempTreeData = genChildren(rootNode); return tempTreeData; };