1. let input = [
    2. {id: 1, val: '学校', parentId: null},
    3. {id: 2, val: '班级1', parentId: 1},
    4. {id: 3, val: '班级2', parentId: 1},
    5. {id: 4, val: '学生1', parentId: 2},
    6. {id: 5, val: '学生2', parentId: 3},
    7. ];
    8. let output = {
    9. id: 1,
    10. val: '学校',
    11. parentId: null,
    12. children: [
    13. {
    14. id: 2,
    15. val: '班级1'
    16. }
    17. ]
    18. }
    19. function arrayToTree(array) {
    20. let root = array[0];
    21. array.shift();
    22. let tree = {
    23. id: root.id,
    24. val: root.val,
    25. children: array.length ? toTree(root.id, array) : []
    26. };
    27. return tree;
    28. }
    29. function toTree(parentId, array) {
    30. let children = [];
    31. let len = array.length;
    32. for (let i = 0; i < len; i++) {
    33. let node = array[i];
    34. if (node.parentId === parentId) {
    35. children.push({
    36. id: node.id,
    37. val: node.val,
    38. children: toTree(node.id, array)
    39. })
    40. }
    41. }
    42. return children;
    43. }
    44. console.log(arrayToTree(input))