原创

js一维数组根据pid递归生成树状结构


js一维数组根据pid递归生成树状结构,在前后端分离的项目中,发现有时候吧递归处理交给前端能减少前端工作量,比如这个生产树状图的结构,前端可以自己处理好open、active后再渲染为menu菜单。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. </body>
  9. <script>
  10. let arr = [{
  11. id: 1,
  12. name: '部门1',
  13. pid: 0
  14. },
  15. {
  16. id: 2,
  17. name: '部门2',
  18. pid: 1
  19. },
  20. {
  21. id: 3,
  22. name: '部门3',
  23. pid: 1
  24. },
  25. {
  26. id: 4,
  27. name: '部门4',
  28. pid: 3
  29. },
  30. {
  31. id: 5,
  32. name: '部门5',
  33. pid: 4
  34. },
  35. {
  36. id: 6,
  37. name: '部门6',
  38. pid: 0
  39. },
  40. ];
  41. //方法一 (递归)
  42. function arrayToTree(array, pid) {
  43. let result = []
  44. array.forEach(item => {
  45. if (item.pid == pid) {
  46. item.children = arrayToTree(array, item.id)
  47. result.push(item)
  48. }
  49. })
  50. return result
  51. }
  52. let treeArray = arrayToTree(arr, 0)
  53. console.log('treeArray', treeArray)
  54. //方法二
  55. function toTree(data) {
  56. let result = []
  57. let map = {};
  58. data.forEach(item => {
  59. map[item.id] = item;
  60. });
  61. console.log('map', map)
  62. data.forEach(item => {
  63. let parent = map[item.pid];
  64. if (parent) {
  65. (parent.children || (parent.children = [])).push(item);
  66. } else {
  67. result.push(item);
  68. }
  69. });
  70. return result;
  71. }
  72. console.log('toTree(arr)', toTree(arr))
  73. </script>
  74. </html>
留言反馈
问题反馈渠道,如有软件无法下载或者其他问题可反馈。【由于某种原因,目前留言不展示】
用户需要登录后才能留言反馈