Stories

Detail Return Return

數組轉化為樹 - Stories Detail

將一個數組轉換為一棵樹可以通過遞歸實現。假設我們有一個包含父節點與子節點關係的數組,如下所示:

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
          }
        ]
      }
    ]
  }
]
user avatar tianmiaogongzuoshi_5ca47d59bef41 Avatar jingdongkeji Avatar linx Avatar huajianketang Avatar u_17443142 Avatar zero_dev Avatar shuirong1997 Avatar dunizb Avatar ccVue Avatar tanggoahead Avatar Asp1rant Avatar Poetwithapistol Avatar
Favorites 87 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.