0

I have to convert an array of objects containing paths into a hierarchy tree list. The paths looks like this: "1/3/2", where 1 is the parent of 3, 3 is the parent of 2 and so on. The depth of the hierarchy and number of children is unlimited, meaning it could look like this: "1/3/2/2/33/33/444/1" or this: "2/".

The array I have right now looks likes this:

[
      {
          id: 1,
          path: "1",
      },
      {
        id: 2,
        path: "1/1/1",
      },
      {
        id: 3,
        path: "1/1",
      },
      {
        id: 4,
        path: "1/1/2",
      },
      {
        id: 5,
        path: "2/1",
      },
      {
        id: 6,
        path: "2/2",
      },
      {
        id: 7,
          path: "2/",
      }
  ]

And I need it to look like this:

[
        {
          id: 1,
          path: "1/",
          children: [
            {
              id: 3,
              path: "1/1",
              children: [
                {
                  id: 2,
                  path: "1/1/1",
                },
                {
                  id: 4,
                  path: "1/1/2",
                }
              ]
            }
          ]
        },
        {
          id: 7,
          path: "2/",
          children: [
            {
              id: 5,
              path: "2/1",
            },
            {
              id: 6,
              path: "2/2",
            },
          ]
        }
      ]

I am trying hard to come up with a good solution to solve this but I could really need som help

3
  • 1
    Share any attempt? Commented Jan 12, 2023 at 16:22
  • Part of the problem is that your path structure is inconsistent. It would be less confusing to solve this if the path of root items did not end with a / Commented Jan 12, 2023 at 16:46
  • “I need help” is not a question we can answer. Commented Jan 14, 2023 at 23:29

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.