数组数据转树形数据

109 阅读1分钟

方法一 封装工具函数 xx.js 然后调用

 // 把平铺的数组结构转成树形结构
 export function transDataToTreeData(arr) {
// 需求;把平铺的数组结构转成树形结构
// 步骤:
// 1. 遍历数组中的对象,给每一个对象添加children树形,值    默认是空数组

const mapObj = {}
arr.forEach(item => {
// 1.1 判断item对象中是否有children属性,如果没有,就添加一个
if (!item.children) {
  item.children = []
}
// 2. 为了方便找数据,创建映射对象,取出item的id作为健,值存的就是对象item本身
mapObj[item.id] = item
})
console.log(arr)
console.log('mapObj', mapObj)
// 3 将平铺的数据转树形的结构
const new_arr = [] // 存放属性结构的数据

arr.forEach(item => {
// 根据pid找父级---mapObj中找父级
 const parent = mapObj[item.pid]
 //   parent 返回的结果 undefind  ,就说明此时的item是一级的数据
//   parent 返回的结果 对象(item的父级) 此时就说明item二级的数据
 if (parent) {
  //  此时就说明item二级的数据,需要添加到父级的children属性中
  parent.children.push(item)
} else {
  // parent 返回的结果 undefind  ,就说明此时的item是一级的数据,就直接将一级的数据添加到新数组中
  new_arr.push(item)
}
})

// console.log('new_arr',new_arr);
return new_arr
 }

方法二 : 导包方法转换

  1. 下包 npm install array-to-tree -S

  2. utils工具函数中定义函数

    import arrayToTree from 'array-to-tree'
    export function transArray(arr) {
      return arrayToTree(arr, {
        parentProperty: 'pid',
        customID: 'id'
      })
    }
    复制代码
    
  3. 组件中使用 transArray()

import { transArray } from '@/utils'
data() {
  return {
    data: [],
  }
},
 methods: {
  //  发送请求获取组织架构数据列表
  async loadDep() {
    const res = await getDepartments()
    if (res.code === 10000) {
       // 成功后获取数据后转换树形
      this.data = transArray(res.data.depts)
    }
  }
}