乐趣区

关于前端:数组转化为树

将一个数组转换为一棵树能够通过递归实现。假如咱们有一个蕴含父节点与子节点关系的数组,如下所示:

const arr = [{ id: 1, name: 'A', parent_id: null},
    {id: 2, name: 'B', parent_id: 1},
    {id: 3, name: 'C', parent_id: 2},
    {id: 4, name: 'D', parent_id: 1},
    {id: 5, name: 'E', parent_id: 4},
    {id: 6, name: 'F', parent_id: 3},
];

当初咱们要将这个数组转换为一棵树,咱们须要做以下步骤:

  1. 遍历数组,找到根节点,即 parent_idnull的节点,将它们保留在一个新数组中。
  2. 对于每个根节点,递归地查找它的子节点。
  3. 对于每个子节点,将它退出其父节点的 children 属性中。

上面是转换为树的实现代码:

function buildTree(arr, parent_id = null) {let tree = [];

  // 遍历数组,找到根节点
  arr.forEach(node => {if (node.parent_id === parent_id) {
      
      // 递归查找子节点
      const children = buildTree(arr, node.id);

      // 如果存在子节点,增加到父节点的 children 属性中
      if (children.length) {node.children = children;}

      // 将节点增加到树中
      tree.push(node);
    }
  });

  return tree;
}

const arr = [{ id: 1, name: 'A', parent_id: null},
  {id: 2, name: 'B', parent_id: 1},
  {id: 3, name: 'C', parent_id: 2},
  {id: 4, name: 'D', parent_id: 1},
  {id: 5, name: 'E', parent_id: 4},
  {id: 6, name: 'F', parent_id: 3},
];

const tree = buildTree(arr);

console.log(JSON.stringify(tree, null, 2));

输入后果为:

[
  {
    "id": 1,
    "name": "A",
    "parent_id": null,
    "children": [
      {
        "id": 2,
        "name": "B",
        "parent_id": 1,
        "children": [
          {
            "id": 3,
            "name": "C",
            "parent_id": 2,
            "children": [
              {
                "id": 6,
                "name": "F",
                "parent_id": 3
              }
            ]
          }
        ]
      },
      {
        "id": 4,
        "name": "D",
        "parent_id": 1,
        "children": [
          {
            "id": 5,
            "name": "E",
            "parent_id": 4
          }
        ]
      }
    ]
  }
]
退出移动版