Skip to content

Instantly share code, notes, and snippets.

@zmts
Created August 15, 2023 09:37
Show Gist options
  • Save zmts/61801ef3d4112877fddb5910aefe80f9 to your computer and use it in GitHub Desktop.
Save zmts/61801ef3d4112877fddb5910aefe80f9 to your computer and use it in GitHub Desktop.
Build tree from flat array

Build tree from flat array

function buildTree(nodes, parentId = null) {
  const tree = [];
  for (const node of nodes) {
    if (node.parentId === parentId) {
      const children = buildTree(nodes, node.id);
      if (children.length) {
        node.children = children;
      }
      tree.push(node);
    }
  }
  return tree;
}
const flatArray = [
  { id: 1, name: "Node 1", parentId: null },
  { id: 2, name: "Node 1.1", parentId: 1 },
  { id: 3, name: "Node 1.1.1", parentId: 2 },
  { id: 4, name: "Node 4", parentId: null },
  { id: 5, name: "Node 4.1", parentId: 4 },
  { id: 6, name: "Node 4.1.1", parentId: 5 },
];

const tree = buildTree(flatList);
console.log(JSON.stringify(tree, null, 2));
[
  {
    "id": 1,
    "name": "Node 1",
    "parentId": null,
    "children": [
      {
        "id": 2,
        "name": "Node 1.1",
        "parentId": 1,
        "children": [
          {
            "id": 3,
            "name": "Node 1.1.1",
            "parentId": 2
          }
        ]
      }
    ]
  },
  {
    "id": 4,
    "name": "Node 4",
    "parentId": null,
    "children": [
      {
        "id": 5,
        "name": "Node 4.1",
        "parentId": 4,
        "children": [
          {
            "id": 6,
            "name": "Node 4.1.1",
            "parentId": 5
          }
        ]
      }
    ]
  }
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment