convert flat data to nested object using slug

I have a flatten data like this that has slug property and I have to convert it to a nested object based on this field:

[
    {
        "id": "e4679a79-48b6-5783-a42f-e4b5a1a4a206",
        "slug": "root/01-topic",
        "frontmatter": {
            "title": "Topic 1"
        }
    },
    {
        "id": "b6cd27c5-8786-5f3f-ae60-7dffcb002d6c",
        "slug": "root/02-topic",
        "frontmatter": {
            "title": "Topic 2"
        }
    },
    {
        "id": "eca8b1c5-30a8-54e3-a3e9-7c482ae9d450",
        "slug": "root/01-section/01-topic",
        "frontmatter": {
            "title": "Topic 1"
        }
    },
    {
        "id": "7bb24e88-8e54-5722-93f1-185bf0f1dd6c",
        "slug": "root/01-section/01-subsection/01-topic",
        "frontmatter": {
            "title": "Topic 1"
        }
    },
    {
        "id": "e93bf045-1798-54d2-a2bc-d5a2eb12a49d",
        "slug": "root/01-section/01-subsection/02-topic",
        "frontmatter": {
            "title": "Topic 2"
        }
    },
    {
        "id": "3ac918f1-31af-501e-bc98-37b33d2bccbd",
        "slug": "root/02-section/01-subsection/01-topic",
        "frontmatter": {
            "title": "Topic 3"
        }
    },
    {
        "id": "1c9021a2-d346-57b8-9586-a48e7e3eb54f",
        "slug": "root/02-section/01-title",
        "frontmatter": {
            "title": "Subsection 1"
        }
    },
   
    ]

and I want to convert it to a new structure that has cildrens so I can render them on the screen to users

[
  { id: "", slug: "root/topic-01", title: "Topic 1" },
  { id: "", slug: "root/topic-02", title: "Topic 2" },
  {
    id: "",
    slug: "root/section-01",
    title: "Topic 2",
    children: [
      { id: "", slug: "root/section-01/topic-01", title: "Topic 1" },
      {
        id: "",
        slug: "root/section-01/subsection-01",
        title: "Topic 1",
        children: [
          {
            id: "",
            slug: "root/section-01/subsection-01/topic-01",
            title: "Topic 1",
          },
        ],
      },
    ],
  },
];

I think that I need to use recursive and having a root node and childrens to it but do not know how to it exactly

can anyone help?