首页

Javascript

Html
Css
Node.js
Electron
移动开发
小程序
工具类
服务端
浏览器相关
前端收藏
其他
关于

JS生成树形目录结构菜单(无限级)

2020年02月14日 发布 阅读(132) 作者:Jerman

JS非递归形式生成树形菜单,可生成无限级

直接上代码吧,可直接复制到浏览器运行一下,有问题欢迎指出

  1. // 原始数据代码
  2. const list = [
  3. {
  4. parentId: null,
  5. target: "_blank",
  6. open: false,
  7. sort: 0,
  8. disabled: false,
  9. name: "1",
  10. url: "/menu",
  11. icon: "aaa",
  12. remark: "fafsa",
  13. id: 19,
  14. createTime: "1579508935022"
  15. },
  16. {
  17. parentId: 19,
  18. target: "_blank",
  19. open: false,
  20. sort: 0,
  21. disabled: false,
  22. name: "2",
  23. url: "/menu",
  24. icon: "aaa",
  25. remark: "fafsa",
  26. id: 191,
  27. createTime: "1579508935022"
  28. },
  29. {
  30. parentId: 191,
  31. target: "_blank",
  32. open: false,
  33. sort: 0,
  34. disabled: false,
  35. name: "3",
  36. url: "/menu",
  37. icon: "aaa",
  38. remark: "fafsa",
  39. id: 192,
  40. createTime: "1579508935022"
  41. },
  42. {
  43. parentId: 192,
  44. target: "_self",
  45. open: false,
  46. sort: 0,
  47. disabled: false,
  48. name: "4",
  49. url: "/aklfdlsa",
  50. id: 22,
  51. createTime: "1579509092433"
  52. },
  53. {
  54. parentId: 22,
  55. target: "_self",
  56. open: false,
  57. sort: 0,
  58. disabled: false,
  59. name: "5",
  60. url: "/aklfdlsa",
  61. id: 23,
  62. createTime: "1579509094083"
  63. },
  64. {
  65. parentId: null,
  66. target: "_self",
  67. open: false,
  68. sort: 0,
  69. disabled: false,
  70. name: "5",
  71. url: "/aklfdlsa",
  72. id: 1000,
  73. createTime: "1579509094083"
  74. },
  75. {
  76. parentId: 1000,
  77. target: "_self",
  78. open: false,
  79. sort: 0,
  80. disabled: false,
  81. name: "5",
  82. url: "/aklfdlsa",
  83. id: 1001,
  84. createTime: "1579509094083"
  85. },
  86. {
  87. parentId: 1000,
  88. target: "_self",
  89. open: false,
  90. sort: 0,
  91. disabled: false,
  92. name: "5",
  93. url: "/aklfdlsa",
  94. id: 1002,
  95. createTime: "1579509094083"
  96. }
  97. ];
  98. function toTree(data, idName, parentIdName) {
  99. const id = idName || "id";
  100. const parentId = parentIdName || "parentId";
  101. // 删除 所有 children,以防止多次调用
  102. data.forEach(function(item) {
  103. delete item.children;
  104. });
  105. // 将数据存储为 以 id 为 KEY 的 map 索引数据列
  106. const map = {};
  107. data.forEach(function(item) {
  108. map[item[id]] = item;
  109. });
  110. const menu = [];
  111. data.forEach(function(item) {
  112. // 在map中找到当前项的父级菜单
  113. const parent = map[item[parentId]];
  114. if (parent) {
  115. // 如果父级菜单存在,则将当前项存入父级的children
  116. // 如果父级的children不存在,初始化为空数组[]后再存入
  117. (parent.children || (parent.children = [])).push(item);
  118. } else {
  119. // 如果父级菜单不存在,则做为顶级菜单存入
  120. menu.push(item);
  121. }
  122. });
  123. return menu;
  124. }
  125. const menu = toTree(list);
  126. console.log(menu);
版权声明:本站文章除特别声明外,均采用署名-非商业性使用-禁止演绎 4.0 国际 许可协议,如需转载,请注明出处

评论

  •