首页 > 其他分享 >数组转树

数组转树

时间:2023-09-06 16:01:19浏览次数:38  
标签:const pid list children itemMap 数组 转树 id

const list = [
  {id: 1, name: '部门1', pid: 0},
  {id: 2, name: '部门1-1', pid: 1},
  {id: 3, name: '部门1-2', pid: 1},
  {id: 4, name: '部门1-1-1', pid: 2},
  {id: 5, name: '部门1-2-1', pid: 3},
  {id: 6, name: '部门2', pid: 0},
  {id: 7, name: '部门2-1', pid: 6},
  {id: 8, name: '部门3', pid: 0},
]

递归实现

// 递归查找获取子节点
const getChild = (list, result, pid) => {
  for(const item of list) {
    if(item.pid === pid) {
      const newItem = { ...item, children: [] };
      result.push(newItem);
      getChild(list, newItem.children, item.id);
    }
  }
}
// 调用递归实现
const listToTree = (list, pid) => {
  const result = [];
  getChild(list, result, pid);
  return result;
}
listToTree(list, 0)

Map对象实现

const listToTree = (list) => {
  // 最终树形结构输出的结果
  const result = [];
  const itemMap = {};
  for(const item of list) {
    const id = item.id;
    const pid = item.pid;
    if(!itemMap[id]) {
      itemMap[id] = {
        children: [],
      };
    }
    itemMap[id] = {
      ...item,
      children: itemMap[id]["children"],
    };
    const treeItem = itemMap[id];
    if(pid === 0) {
      result.push(treeItem)
    } else {
      if(!itemMap[pid]) {
        itemMap[pid] = {
          children: []
        }
      }
      itemMap[pid].children.push(treeItem);
    }
  }
  return result;
}

listToTree(list, 0)

filter实现

const listToTree = (list, key) => {
  const tree = list.filter(function(parent) {
    // 返回每一项得的子级数据
    const branchArr = list.filter((child) => parent.id === child[key]);
    parent.children = [];
    // 如果存在子级,则给父级添加一个children属性并赋值
    if (branchArr.length > 0) {
      parent.children = branchArr;
    }
    // 返回第一层
    return parent[key] == 0;
  });
  return tree;
}
// 传入原始数据和父级pid的key
listToTree(list, 'pid')

标签:const,pid,list,children,itemMap,数组,转树,id
From: https://blog.51cto.com/u_15930000/7387970

相关文章

  • 【C语言进阶】指针数组 —— 数组指针
    (文章目录)......
  • SpringBoot启动报数组下标越界
    问题描述:启动读取配置文件时报错关键字:ERRORorg.springframework.boot.SpringApplication-Applicationrunfailedjava.lang.ArrayIndexOutOfBoundsException:-1ConnectedtothetargetVM,address:'127.0.0.1:58753',transport:'socket'2023-09-0611:09......
  • java中String和数组的长度
    数组的长度是lengthString的长度是length()在Java中,数组是引用数据类型,不是类,因此也是读取固有的length属性得到数组长度,它没有length()方法。但是,java中的String类型是jdk中已经封装好的final类,类就有属性和方法,只是String没有length属性,只有length()方法。......
  • 剑指 Offer 42. 连续子数组的最大和
    输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)。 示例1:输入:nums=[-2,1,-3,4,-1,2,1,-5,4]输出:6解释:连续子数组[4,-1,2,1]的和最大,为6。classSolution{publicintmaxSubArray(int[]nums){......
  • C语言数组(12)——写一个三子棋游戏(3)
    一.回顾我们上篇文章主要介绍了棋盘的打印,我们用到了DisplayBoard()函数,那么我们现在就需要来实现玩家下棋这一操作二.玩家下棋功能的实现与前几个函数一样我们将玩家下棋功能代码封装成一个函数,命名为PlayerMove()函数,我们前面说过玩家下棋的本质就是将数据填进二维数组中的元素中......
  • 在 PHP 数组中的两个字符串之间切换
    在PHP中,你可以使用array_flip()函数和条件语句来在数组中的两个字符串之间进行切换。以下是一个示例://创建一个数组,包含两个字符串的映射关系$mapping=array('string1'=>'value1','string2'=>'value2');//定义当前需要切换的字符串$currentString='string......
  • 前端编程题(一):数组
    手写数组常见方法//数组mapArray.prototype.myMap=function(callback){constarr=[]for(leti=0;i<this.length;i++){arr[i]=callback(this[i],i);}returnarr;}//数组filterArray.prototype.myFilter=function(callback){const......
  • python 对象数组,根据指定字段条件过滤数据,并排序升序
    在Python中,你可以使用`filter()`函数和`sorted()`函数来根据指定字段的条件过滤并排序对象数组。以下是示例代码,演示如何根据指定字段条件过滤并按升序排序对象数组:```pythonobj_arr=[{'id':1,'name':'John'},{'id':2,'name':'Jane'},{'id':......
  • python 数字数组升序排序
    在Python中,你可以使用内置的`sorted()`函数对数字数组进行升序排序。以下是示例代码,演示如何对数字数组进行升序排序:```pythonnums=[5,3,8,2,1,9,4]sorted_nums=sorted(nums)print(sorted_nums)#输出:[1,2,3,4,5,8,9]```在这个示例中,我们使用`sorted()......
  • 数组去重
    ES5filter点击查看代码functionunique(arr){varres=arr.filter(function(item,index,array){returnarray.indexOf(item)===index})returnres}ES6点击查看代码varunique=arr=>[...newSet(arr)]......