Need your help guys
I have nested object with infinity nesting.
How I can reorganize children
keys to numeric
keys?
From this:
{
children: [
{
taskId: "e3f241f8-c879-4118-893d-a16715e45308",
opts: {},
children: [
{
taskId: "e3f241f8-c879-4118-893d-a248cae411208",
opts: {},
children: [
taskId: "e3f241f8-c879-4118-89112d-s248cae411208",
opts: {},
children: []
]
}
],
}
],
}
To this:
{
1: {
2: {
3: {
4: ''
}
}
}
}
I’m trying use forEach and recursive function, but any result.
3
Answers
Not sure how much sense this explanation makes but… Here the idea is to loop through a queue that gets built as you go. The items in the queue being the old data object and a reference to a new one that’s being created as you go. A number gets incremented on each iteration to serve as the new key values. Each iteration a member of the queue gets removed and serves as the basis to add more items to the queue if the current object has children.
The following numbers the items horizontally down the tree (or breadth-first / level-order traversal):
This version numbers the items by going down as far as possible first (or depth-first traversal):
It seems to work:
I am not sure why it works, but I’ve got some points (may help solving the problem):
Note: I don’t understand what is your question here: what traversal ordering do you want? in BFS or DFS? I am answering in DFS now because you’ve mentioned "recursion".