Answer the question
In order to leave comments, you need to log in
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:
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,
},
];
onChangeselecta. 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 questionAsk a Question
731 491 924 answers to any question