arrayToTree.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. let testData = [
  2. {
  3. groupId: 1,
  4. name: 1,
  5. parentId: ''
  6. },
  7. {
  8. groupId: 2,
  9. name: 2,
  10. parentId: ''
  11. },{
  12. groupId: 3,
  13. name: 3,
  14. parentId: ''
  15. },{
  16. groupId: 4,
  17. name: 1.4,
  18. parentId: 1
  19. },
  20. {
  21. groupId: 5,
  22. name: 1.5,
  23. parentId: 1
  24. },
  25. {
  26. groupId: 6,
  27. name: 1.6,
  28. parentId: 1
  29. },
  30. {
  31. groupId: 7,
  32. name: 6.7,
  33. parentId: 6
  34. },
  35. {
  36. groupId: 8,
  37. name: 6.8,
  38. parentId: 6
  39. },
  40. {
  41. groupId: 9,
  42. name: 2.9,
  43. parentId: 2
  44. },
  45. {
  46. groupId: 10,
  47. name: 2.10,
  48. parentId: 2
  49. }
  50. ];
  51. function arrayToTree(array,oneLevelId='',fieldKey,parentKey){
  52. // 数组转tree
  53. function loop(_arr,parentId){
  54. return _arr.reduce((acc,cur,ind,arr)=>{
  55. if(cur[parentKey] === parentId){
  56. acc.push(cur);
  57. cur.children = loop(arr,cur['fieldKey']);
  58. }
  59. return acc;
  60. },[]);
  61. }
  62. return loop(array,oneLevelId);
  63. }
  64. function test(){
  65. arrayToTree(testData);// array [{…}, {…}, {…}]
  66. }