首页 > 其他分享 >请封装⼀个⽅法,将以下树形数据转换成期望的格式

请封装⼀个⽅法,将以下树形数据转换成期望的格式

时间:2023-04-12 09:11:55浏览次数:35  
标签:转换成 arr 封装 res pid children item 树形 id

转化前 const list = [ {id:1}, {pid:1,id:2}, {id:3}, {pid:3,id:4}, {pid:4,id:5} ] 转化后 [{ id:1, children:[{ pid:1, id:2 }] }, { id:3, children:[{ pid:3, id:4, children:[{ pid:4, id:5 }] }] }] getChildren(arr, id) { const res = [];//根据数据⼀致性,定义返回的结果 if (!id) { //如果没有传⼊id代表查找第⼀层数据 res.push(...arr.filter((item) => !item.pid)); } else {//传⼊id时,代表查找⼦节点 res.push(...arr.filter((item) => item.pid === id)); } res.forEach((item) => {//查找后要递归每个节点,从⽽实现children属性 const children = getChildren(arr, item.id) if (children.length) {//如果查找不到就不⽤赋值了,否则会多⼀个空数组 item.children = children; } }); return res; } //调⽤执⾏,list是转换前的数组,返回值是转换后的数组 getChildren(list)

标签:转换成,arr,封装,res,pid,children,item,树形,id
From: https://www.cnblogs.com/Daguaishou0704/p/17308606.html

相关文章

  • C++复习第五天(封装)
    封装练习,设计一个学生类,属性有姓名和学号,可以给姓名和学号赋值,可以显示姓名和学号。#include<iostream>#include<string>usingnamespacestd;classStudent{public://类中的属性和行为,我们统一称为成员stringm_name;intm_Id;voidshowStudent......
  • java将Word转换成PDF三种方法
    java将Word转换成PDF三种方法原文链接:https://blog.csdn.net/weixin_38409915/article/details/125317664网上有很多将Word转换成PDF的方式,这里找了三种比较简单的工具:poi、jacob和aspose。1.POI依赖<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-o......
  • 康复训练の树形DP
    所有代码的开头头文件,宏定义和命名空间如下#include<bits/stdc++.h>#defineTptemplate<typenameTy>#defineTstemplate<typenameTy,typename...Ar>#definelllonglong#defineCIconstint#defineRIint#defineWwhile#definegcgetchar#definemax(x,y)......
  • 封装导出Excel文件
    utils/exportexcel.jsimport{parseTime}from'@/utils/format';import{Message}from'element-ui';/***导出Excel文件*@param{*}data文件数据流*@param{String}filePrefix文件前缀名*@param{String}fileSuffix文件后缀名*/exportfuncti......
  • 封装,继承,多态
    封装该露的露,该藏的藏我们程序设计要追求“高内聚,低耦合”。高内聚就是类的内部数据操作细节自己完成,不允许外部干涉;低耦合:仅暴露少量的方法给外部使用。封装(数据的隐藏)通常,应禁止直接访问一个对象中数据的实际表示,而应通过操作接口来访问,这称为信息隐藏。记住这句话就够......
  • 封装统一请求状态返回Result
    1、测试数据publicclassTest{publicstaticvoidmain(String[]args){System.out.println("Response.success(ErrorEnum.SUCCESS)="+Response.success(ErrorEnum.SUCCESS));System.out.println("Response.success(ErrorEnum.FA......
  • el-table树形数据与懒加载
    <template><divclass="page"><divclass="page-box"><h3style="margin-top:0">类目/榜单管理</h3><el-inputplaceholder="请输入关键字"v-model="keyWord"style="......
  • 搜索二叉树转换成双向链表
    搜索二叉树:每个节点的左子树的值都小于当前节点,右子树的节点值都大于当前节点。其中序遍历就是一个有序的序列转化成双向链表,需要记录一下头节点,和前一个节点,将前一个节点和当前节点相连preheadconvert(pRoot){if(pRoot==null)returnnull;convert(pRoot.left);......
  • .NET Core MongoDB数据仓储和工作单元模式封装
    前言     上一章我们把系统所需要的MongoDB集合设计好了,这一章我们的主要任务是使用.NETCore应用程序连接MongoDB并且封装MongoDB数据仓储和工作单元模式,因为本章内容涵盖的有点多关于仓储和工作单元的使用就放到下一章节中讲解了。仓储模式(Repository )带来的好处是一......
  • 算法-递归三(树形结构)
    publicclassSolution{publicIList<IList<int>>Permute(int[]nums){varrtItem=newList<int>();varvisited=newDictionary<int,bool>();IList<IList<int>>rt=newList<IList<int&......