1. // 把后端传过来的平铺数组数据处理为tree组件需要的树形数据
    2. //方法1
    3. export function tranListToTreeData(list) {
    4. const treeList = []
    5. const map = {}
    6. list.forEach(item => {
    7. item.children = []
    8. map[item.id] = item
    9. })
    10. list.forEach(item => {
    11. const parent = map[item.pid]
    12. if (parent) {
    13. parent.children.push(item)
    14. } else {
    15. treeList.push(item)
    16. }
    17. })
    18. return treeList
    19. }
    20. //方法2
    21. 利用递归数组转树
    22. export function tranListToTreeData(list, rootId = '') {
    23. const children = []
    24. list.forEach(item => {
    25. if (item.pid === rootId) {
    26. children.push(item)
    27. // item.children继续执行这个函数(递归),找item.children的儿子
    28. item.children = tranListToTreeData(list, item.id)
    29. }
    30. })
    31. return children
    32. }