Currently, I am attempting to convert a tree structure provided in the following format:
{"Parent":
{
"Child1": ["toy1"],
"Child2":
{
"Nephew": ["toy2", "toy3"]
}
}
}
into a standardized tree format like this:
{
"name": "root",
"children":
[{"name":"Parent",
"children":
[{
"name":"Child1",
"children": ["toy1"]
},
{
"name":"Child2"
"children":
[{
"name":"Nephew",
"children": ["toy2", "toy3"]
}]
}]
}]
}
Essentially, my goal is to normalize the tree structure.
I have attempted this using the code below:
function recurse(elem) {
if (typeof(elem) !== "object") return elem;
level = [];
for (let part in elem) {
level.push({
name: part,
children: recurse(elem[part])
});
console.log(level);
}
return level;
}
restrucTree = {
name: "root",
children: recurse(tree)
};
However, it seems that there are some issues with the recursion and object construction as the root node (in this case "Parent") is missing from the transformed tree. Additionally, this method fails when the tree branches out into multiple sub-trees, only recognizing the last one. My assumption is that during the recursive stack unwinding, stored objects are being lost, but I can't figure out how to address this problem. If you have any insights on where these errors may be originating from, I would greatly appreciate your input!