K
K
Konstantin P2021-02-12 09:40:33
JavaScript
Konstantin P, 2021-02-12 09:40:33

How to build a tree with a generated nesting level designation key from a flat array?

Questions, as mine has probably already been asked enough. But I still want to ask for help. It is necessary to make a tree from a flat array. (The whole task is in React). Array example and execution below. Objects that have a group-id key will be children (nested), respectively, objects that do not have this key will be root. What is the dimension of the incoming array and what will be the nesting is not known. Googling, I found the listToTree() function, which I adapted a little for myself:

Codepen example

The problem is, I don't know how to add a new key to a certain level. well, for example, at the first nesting level, for all objects the key should be

group
, at the second level
subgroup
, at the third level
device
. Or you can somehow dynamically generate a key like l
level1, level2... leveln
. Why do I need this: I have selects on the page, when I select an element from the first level, I add a new select with children:
60261f85bd975836225974.png
Also, when the selects change, the route changes and a new component is loaded. Array with routes:
const routes = [
  {
    id: 1,
    path: "/",
    component: HomePage,
  },
  {
    id: 2,
    path: "/group/:id",
    component: GroupContentPage,
  },
  {
    id: 3,
    path: "/group/:id/device/:id",
    component: DeviceContentPage,
  },
  {
    id: 4,
    path: "*",
    component: ErrorPage,
  },
];

So I need to somehow make a new key in the tree with the name of the level, so that I can somehow hook on it and make a route when
onChange
selecta. I'm sorry that I loaded you with such a long description, but I tried to describe the problem more specifically. Thanks in advance!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question