shayloyuki

科技是第一生产力

 

封装公共方法:扁平数组转为树形数组

代码

src/utils/arr.js

/**
 *
 * @param {Array} flatArr 扁平数据
 * @param {string} pid 上级数据的id,常用'pid'
 * @returns
 */
// 扁平数组转为树形数组
export function arrToTree(flatArr, pid) {
  const res = []
  const map = flatArr.reduce((res, v) => (res[v.id] = v, v.children = [], res), {})
  for (const item of flatArr) {
    if (item[pid] === 0) {
      res.push(item)
      continue
    }
    if (item[pid] in map) {
      const parent = map[item[pid]]
      parent.children = parent.children || []
      parent.children.push(item)
    }
  }
  return res
}

main.js

import { arrToTree } from '@/utils/arr'
// 全局挂载
Vue.prototype.arrToTree = arrToTree

使用
this.nodeData = this.arrToTree(this.nodeArr, 'pid')

参考链接

数组转换成树形结构

posted on 2022-12-23 13:31  shayloyuki  阅读(20)  评论(0编辑  收藏  举报

导航