嵌套、扁平菜单互转

作者:杨润炜
日期:2020/7/7 23:44

今天被一个简单的嵌套、扁平菜单转换问题搞懵,特此记录一下。

  1. const assert = require('assert')
  2. // 扁平菜单
  3. const flatMenu = [
  4. {
  5. id: 13,
  6. name: "菜单3",
  7. parent: 12,
  8. },
  9. {
  10. id: 1,
  11. name: "菜单1",
  12. parent: null,
  13. },
  14. {
  15. id: 12,
  16. name: "菜单2",
  17. parent: 1,
  18. },
  19. {
  20. id: 2,
  21. name: "菜单1-1",
  22. parent: null,
  23. },
  24. {
  25. id: 14,
  26. name: "菜单3-1",
  27. parent: 12,
  28. },
  29. ]
  30. // 嵌套菜单
  31. const nestMenu = [
  32. {
  33. "id": 1,
  34. "name": "菜单1",
  35. "parent": null,
  36. "children": [
  37. {
  38. "id": 12,
  39. "name": "菜单2",
  40. "parent": 1,
  41. "children": [
  42. {
  43. "id": 13,
  44. "name": "菜单3",
  45. "parent": 12,
  46. "children": []
  47. },
  48. {
  49. "id": 14,
  50. "name": "菜单3-1",
  51. "parent": 12,
  52. "children": []
  53. }
  54. ]
  55. }
  56. ]
  57. },
  58. {
  59. "id": 2,
  60. "name": "菜单1-1",
  61. "parent": null,
  62. "children": []
  63. }
  64. ]
  65. // 扁平转嵌套
  66. class FlatToNest {
  67. entry(menuList) {
  68. const res = []
  69. const map = {}
  70. for (const node of menuList) {
  71. node.children = []
  72. map[node.id] = node
  73. }
  74. for (const node of menuList) {
  75. if (node.parent) {
  76. map[node.parent].children.push(node)
  77. } else {
  78. res.push(node)
  79. }
  80. }
  81. return res
  82. }
  83. }
  84. // 嵌套转扁平
  85. class NestToFlat {
  86. entry(menuList) {
  87. let res = []
  88. for (const node of menuList) {
  89. res = res.concat(this.entry(node.children))
  90. res.push(node)
  91. }
  92. return res
  93. }
  94. }
  95. // 测试类
  96. class FlatToNestTest {
  97. run() {
  98. const res = (new FlatToNest()).entry(flatMenu)
  99. assert.deepStrictEqual(res, nestMenu)
  100. }
  101. }
  102. class NestToFlatTest {
  103. run() {
  104. const res = (new NestToFlat()).entry(nestMenu)
  105. assert.deepStrictEqual(res.sort((p, n) => p.id - n.id), flatMenu.sort((p, n) => p.id - n.id))
  106. }
  107. }
  108. function main() {
  109. (new FlatToNestTest()).run();
  110. (new NestToFlatTest()).run();
  111. }
  112. main()

感谢您的阅读!
如果看完后有任何疑问,欢迎拍砖。
欢迎转载,转载请注明出处:http://www.yangrunwei.com/a/111.html
邮箱:glowrypauky@gmail.com
QQ: 892413924