挑战1000道javascript手写题之列表转树形结构(13)

题意描述

有如下的部门信息数据,id表示部门id,pid表示上级部门的id,最高级的部门为部门0,现在要将下面的部门列表转为树形结构。

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

递归实现

  1. 找出列表中的根节点
  2. 递归的在列表中找出每个节点的子节点
  3. 返回根节点的子节点数组
/**
 * 返回一个数组,表示root.children
 * @param {array} rootList 
 * @param {string} id 
 * @param {array} list 
 * @return {array}
 */
function getTreeList(rootList, id, list) {
  for (const item of rootList) {
    if (item.pid === id) {
      list.push(item)
    }
  }
  for (const item of list) {
    item.children = []
    getTreeList(rootList, item.id, item.children)
    if (item.children.length === 0) {
      delete item.children
    }
  }
  return list
}

/**
 1. 返回树形结构
 2. @param {Array<Object>} rootList
 3. @return {Object}
 */
function getTreeData(rootList) {
  const root = rootList.find((item) => !item.hasOwnProperty('pid'))
  const rootChildren = getTreeList(rootList, root.id, [])
  return {
    ...root,
    children: rootChildren
  }
}

测试

let treeData = getTreeData(list)
console.log(JSON.stringify(treeData));

结果

{
  "id": 0,
  "name": "部门0",
  "children": [
    {
      "id": 1,
      "name": "部门1",
      "pid": 0,
      "children": [
        {
          "id": 2,
          "name": "部门2",
          "pid": 1
        },
        {
          "id": 3,
          "name": "部门3",
          "pid": 1,
          "children": [
            {
              "id": 4,
              "name": "部门4",
              "pid": 3,
              "children": [
                {
                  "id": 5,
                  "name": "部门5",
                  "pid": 4
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "id": 6,
      "name": "部门6",
      "pid": 0
    }
  ]
}

非递归方法

  1. 遍历列表
  2. 对于列表的每一项,再去遍历一遍列表,筛选出其子节点,同时找出根节点
  3. 返回根节点
/**
 * 返回树形结构
 * @param {Array<Object>} rootList
 * @return {Object} 
 */
function getTreeData_2(rootList) {
  let root = null
  for (const item of rootList) {
    const children = rootList.filter((ele) => ele.pid === item.id)
    if (children.length) {
      item.children = children
    }
    if (item.pid === undefined) {
      root = item
    }
  }
  return root
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端之仙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值