二开常见人资项目!!!!小节1 递归转化树形结构

本文介绍了在处理组织架构数据时,如何将后端提供的平铺数据转换为树形结构。通过一个JavaScript函数`buildTree`实现了递归转换,该函数基于id、name和parent_id属性。示例代码展示了如何创建和测试这个转换过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        今天在一个二开的项目中遇到一个很常见的小功能, 把后端传过来组织架构之类平铺的数据,转化成树形结构! 这个其实可和发给咱们数据的后端兄弟商量一下,看他能不能改一下数据,我们就可以直接拿过来用了. 当然如果他不同意,或许水平不行,他不会~那就只能咱们自己干了, 也不难.

idnameparent_id 三个属性,它们分别表示节点的唯一标识、节点名称和节点的父节点标识。

function buildTree(data, parentId) {
  let tree = [];
  for (let i = 0; i < data.length; i++) {
    if (data[i].parent_id === parentId) {
      let node = {
        id: data[i].id,
        name: data[i].name,
        children: buildTree(data, data[i].id)
      };
      tree.push(node);
    }
  }
  return tree;
}

 

随便搞点假数据试验一下

let data = [
  {id: 1, name: '节点1', parent_id: null},
  {id: 2, name: '节点2', parent_id: 1},
  {id: 3, name: '节点3', parent_id: 1},
  {id: 4, name: '节点4', parent_id: 2},
  {id: 5, name: '节点5', parent_id: 3},
  {id: 6, name: '节点6', parent_id: 3},
  {id: 7, name: '节点7', parent_id: 4},
];

let tree = buildTree(data, null);
console.log(JSON.stringify(tree, null, 2));

你就会的到一个新数组

[
  {
    "id": 1,
    "name": "节点1",
    "children": [
      {
        "id": 2,
        "name": "节点2",
        "children": [
          {
            "id": 4,
            "name": "节点4",
            "children": [
              {
                "id": 7,
                "name": "节点7",
                "children": []
              }
            ]
          }
        ]
      },
      {
        "id": 3,
        "name": "节点3",
        "children": [
          {
            "id": 5,
            "name": "节点5",
            "children": []
          },
          {
            "id": 6,
            "name": "节点6",
            "children": []
          }
        ]
      }
    ]
  }
]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值