JavaScript 一维数组转树形结构 算法函数

由于业务中经常要用到一维数组转树形结构的函数特此记录下

我们经常从服务器中拿到如下的一维数组

var nodes = [
  {"id":1,"pId":0,"name":"父节点1 - 展开","open":true},
  {"id":11,"pId":1,"name":"父节点11 - 折叠"},
  {"id":12,"pId":1,"name":"父节点12 - 折叠"},
  {"id":13,"pId":1,"name":"父节点13 - 没有子节点"},
  {"id":2,"pId":0,"name":"父节点2 - 折叠"},
  {"id":21,"pId":2,"name":"父节点21 - 展开","open":true},
  {"id":22,"pId":2,"name":"父节点22 - 折叠"},
  {"id":23,"pId":2,"name":"父节点23 - 折叠"},
  {"id":3,"pId":0,"name":"父节点3 - 没有子节点"}
];

但是在业务上我们想要的是树形文档结构的数组树

如下

var tree = [
  {
    "id": 1,
    "pId": 0,
    "name": "父节点1 - 展开",
    "open": true,
    "children": [
      {
        "id": 11,
        "pId": 1,
        "name": "父节点11 - 折叠"
      },
      {
        "id": 12,
        "pId": 1,
        "name": "父节点12 - 折叠"
      },
      {
        "id": 13,
        "pId": 1,
        "name": "父节点13 - 没有子节点"
      }
    ]
  },
  {
    "id": 2,
    "pId": 0,
    "name": "父节点2 - 折叠",
    "children": [
      {
        "id": 21,
        "pId": 2,
        "name": "父节点21 - 展开",
        "open": true
      },
      {
        "id": 22,
        "pId": 2,
        "name": "父节点22 - 折叠"
      },
      {
        "id": 23,
        "pId": 2,
        "name": "父节点23 - 折叠"
      }
    ]
  },
  {
    "id": 3,
    "pId": 0,
    "name": "父节点3 - 没有子节点"
  }
]

1.使用递归方式将 nodes –> tree

function getTree(data, root, idTxt, pidTxt, pushTxt) {
    var idTxt = idTxt || 'id';
    var pidTxt = pidTxt || 'pid';
    var pushTxt = pushTxt || 'children';
    // 递归方法
    function getNode(id) {
      var node = []
      for (var i = 0; i < data.length; i++) {
        if (data[i][pidTxt] == id) {
          data[i][pushTxt] = getNode(data[i][idTxt])
          node.push(data[i])
        }
      }
      if (node.length == 0) {
        return
      } else {
        return node
      }
    }
    // 使用根节点
    return getNode(root)
  }

    原文作者:advsets
    原文地址: https://www.jianshu.com/p/bdaffff30b31
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞