美文网首页
使用递归将一维数组转换成tree 结构

使用递归将一维数组转换成tree 结构

作者: 冰落寞成 | 来源:发表于2024-03-21 14:53 被阅读0次

list 转换成tree

  /**
   * 将普通数组转换成tree
   */
    listToTree (list, pid = 0) {
      const tree = []
      list.forEach(item => {
        if (item.pid === pid) {
          const children = this.listToTree(list, item.id)
          if (children.length > 0) {
            item.children = children
          }
          tree.push(item)
        }
      })
      return tree
    },
export const arrayToTree=({list=[], pid=0,parentIdKey="parentId",childrenKey='id'}={})=>{
    const tree = []
    list.forEach(item => {
      console.log('item[parentIdKey]',item[parentIdKey],pid,item[parentIdKey] === pid)
      if (item[parentIdKey] === pid) {
        const children = arrayToTree({list, pid:item[childrenKey],parentIdKey,childrenKey})
        if (children.length > 0) {
          item.children = children
        }
        tree.push(item)
      }
    })
    return tree
}

相关文章

  • js玩转树结构

    树结构转换成数组treeToArray(tree) {let arr = [];let expand = (tre...

  • 树状结构和扁平结构的相互转换(js, javascript,df

    1. 树状结构转换成扁平结构 有如下树状结构 实现效果 使用dfs遍历 递归 非递归 使用bfs遍历 层序遍历 2...

  • js数组平铺和树形结构的转换

    将一个平铺的数据转换成一个树形的数据结构 将树形结构的数组转换成平铺的数组

  • Javascript数组扁平化

    数组的扁平化是指将多维数组转换成一位数组。 递归方法 用数组的reduce方法来简化递归操作 用数组的toStri...

  • js扁平化

    扁平化就是将数组依次递归处理,将其转换成一阶数组,例如:【1,【2】,【【3,4】】,【【【5】】】】------...

  • 常用的工具函数

    格式化时间 将url请求参数转为json格式 父子关系的数组转换成树形结构数据 树形结构数据转换成父子关系的数组 ...

  • Js递归数组展平

    遇到多个嵌套的数组,将嵌套的数组中的元素全部展开到最外层的数组中,可以使用递归来解决这个问题。 什么是递归? 递归...

  • 递归tree 结构

    得到

  • python中的列表与数组转换

    将列表转换成数组或者数组转换成列表,操作如下(使用函数array 和 tolist): from numpy im...

  • 命令行中 tree 的多重实现

    解题思路 利用递归,将目录转换成 {:name: ".", :children: []} 结构 对于第一层目录名,...

网友评论

      本文标题:使用递归将一维数组转换成tree 结构

      本文链接:https://www.haomeiwen.com/subject/hconbdtx.html