tree数据格式

  1. export default [
  2. {
  3. "title": "前端开发",
  4. "key": "web",
  5. "pid": 0,
  6. "id": 1,
  7. "children": [
  8. {
  9. "title": "React",
  10. "key": "react",
  11. "pid": 1,
  12. "id": 10,
  13. "children": [
  14. {
  15. "title": "虚拟DOM",
  16. "key": "vdom",
  17. "pid": 10,
  18. "id": 101
  19. },
  20. {
  21. "title": "组件化",
  22. "key": "component",
  23. "pid": 10,
  24. "id": 102
  25. },
  26. {
  27. "title": "react生命周期",
  28. "key": "lifecycle",
  29. "pid": 10,
  30. "id": 103
  31. }
  32. ]
  33. },
  34. {
  35. "title": "Vue",
  36. "key": "vue",
  37. "pid": 1,
  38. "id": 12,
  39. "children": [
  40. {
  41. "title": "vuex",
  42. "key": "vuex",
  43. "pid": 12,
  44. "id": 121
  45. },
  46. {
  47. "title": "vue-router",
  48. "key": "vue-router",
  49. "pid": 12,
  50. "id": 122
  51. },
  52. {
  53. "title": "vue模板",
  54. "key": "template",
  55. "pid": 12,
  56. "id": 123
  57. }
  58. ]
  59. },
  60. {
  61. "title": "ES6",
  62. "key": "es6",
  63. "id": 13,
  64. "pid": 1
  65. }
  66. ]
  67. },
  68. {
  69. "title": "后端开发",
  70. "key": "back",
  71. "pid": 0,
  72. "id": 2,
  73. "children": [
  74. {
  75. "title": "搜索",
  76. "key": "search",
  77. "pid": 2,
  78. "id": 21,
  79. "children": [
  80. {
  81. "title": "缓存",
  82. "key": "cache",
  83. "pid": 21,
  84. "id": 211
  85. },
  86. {
  87. "title": "数据库",
  88. "key": "sql",
  89. "pid": 21,
  90. "id": 212
  91. },
  92. {
  93. "title": "Server",
  94. "key": "server",
  95. "pid": 21,
  96. "id": 213
  97. }
  98. ]
  99. },
  100. {
  101. "title": "全文检索",
  102. "key": "elastic",
  103. "pid": 2,
  104. "id": 22
  105. }
  106. ]
  107. },
  108. {
  109. "title": "产品运营",
  110. "key": "operation",
  111. "pid": 0,
  112. "id": 3
  113. }
  114. ]

扁平化tree数组

  1. export const isArray = array => Array.isArray(array) && array.length
  2. export const flatArray = array => {
  3. if (!isArray(array)) return [];
  4. return array.reduce((memo, next) => {
  5. const flat = isArray(next.children) ? flatArray(next.children) : next;
  6. return memo.concat(flat);
  7. }, []);
  8. };