数组转树形结构的两种实现

简介: 数组转树形结构的两种实现

先假设数组数据:

const arr = [
  { id: '01', name: '张大大', pid: '', job: '项目经理' },
  { id: '02', name: '小亮', pid: '01', job: '产品leader' },
  { id: '03', name: '小美', pid: '01', job: 'UIleader' },
  { id: '04', name: '老马', pid: '01', job: '技术leader' },
  { id: '05', name: '老王', pid: '01', job: '测试leader' },
  { id: '06', name: '老李', pid: '01', job: '运维leader' },
  { id: '07', name: '小丽', pid: '02', job: '产品经理' },
  { id: '08', name: '大光', pid: '02', job: '产品经理' },
  { id: '09', name: '小高', pid: '03', job: 'UI设计师' },
  { id: '10', name: '小刘', pid: '04', job: '前端工程师' },
  { id: '11', name: '小华', pid: '04', job: '后端工程师' },
  { id: '12', name: '小李', pid: '04', job: '后端工程师' },
  { id: '13', name: '小赵', pid: '05', job: '测试工程师' },
  { id: '14', name: '小强', pid: '05', job: '测试工程师' },
  { id: '15', name: '小涛', pid: '06', job: '运维工程师' }
]

递归

/**
     * json格式转树状结构
     * @param   {json}      json数据
     * @param   {String}    一级节点pid
     * @return  {Array}     数组
     */
 transListDataToTreeData(list, root) {
      const arr = [];
      // 1.遍历
      list.forEach((item) => {
        // 2.首次传入空字符串  判断list的pid是否为空 如果为空就是一级节点
        if (item.pid === root) {
          // 找到之后就要去找item下面有没有子节点  以 item.id 作为 父 id, 接着往下找
          const children = transListDataToTreeData(list, item.id);
          if (children.length > 0) {
            // 如果children的长度大于0,说明找到了子节点
            item.children = children;
          }
          // 将item项, 追加到arr数组中
          arr.push(item);
        }
      });
      return arr;
    }
transListDataToTreeData(arr,'')

对象形式

/**
     * json格式转树状结构
     * @param   {json}      json数据
     * @return  {Array}     数组
     */
    transData(arr) {
      let r = [],
        hash = {},
        i = 0,
        j = 0,
        len = a.length;
      for (; i < len; i++) {
        hash[a[i].id] = a[i];
      }
      // console.log(hash,'hash');
      for (; j < len; j++) {
        let aVal = a[j],
          hashVP = hash[aVal.pid];
        aVal.label = aVal.name;
        if (hashVP) {
          !hashVP.children && (hashVP.children = []);
          hashVP.children.push(aVal);
        } else {
          r.push(aVal);
        }
      }
      // console.log(r);
      return r;
    }
transData(arr);


相关文章
|
7天前
|
JavaScript 前端开发
将一维数组转树形
将一维数组转树形
|
7天前
【数据结构】二叉树(遍历,递归)
【数据结构】二叉树(遍历,递归
17 2
|
7天前
|
算法 测试技术 C#
【离散化】【 树状树状 】100246 将元素分配到两个数组中
【离散化】【 树状树状 】100246 将元素分配到两个数组中
|
7天前
|
算法 数据处理 Python
深入理解二叉树:结构、遍历和实现
深入理解二叉树:结构、遍历和实现
深入理解二叉树:结构、遍历和实现
|
10月前
数组转树形结构的两种实现
数组转树形结构的两种实现
29 0
|
9月前
|
存储 算法 编译器
探索二叉树:结构、遍历与应用
什么是二叉树? 二叉树是一种由节点组成的层次结构,其中每个节点最多有两个子节点,分别称为左子节点和右子节点。这种结构使得二叉树在存储和搜索数据时非常高效。二叉树的一个特殊情况是二叉搜索树(Binary Search Tree,BST),它满足左子节点的值小于父节点,右子节点的值大于父节点,这种特性使得在BST中进行查找操作更加高效。
71 0
|
9月前
|
存储 算法 C语言
【数据结构】前中后层序遍历 --二叉树的结构特点与遍历方式
与之前链表的Node类似,所以就不细讲了(给定一个值,malloc其节点,将值存入x,其左右指针置空,返回这个节点值)
54 0
数组转树形结构(递归)
大家好,今天我将向大家分享一下数组转树形结构的方法——递归方法。
|
12月前
树的遍历
树的遍历
C#《数据结构》二叉树的创建和遍历
C#《数据结构》二叉树的创建和遍历
114 0