Let's say I have a typical tree data structure that looks like this:
[
{
att1: 'asdasd',
att2: 42,
att3: true,
subs: [ ...other objects... ]
},
...other objects...
]
It can have any shape and number of nodes, but every node has these three attributes (which have of course different values for each node).
Now, I'd like to create a new tree that would have the exact same hierarchy, but it should hold the data let's say in a format like this:
[
{
data: { att1: 'asdasd', att2: 42, att3: true },
subs: [ ...other objects... ]
},
...other objects...
]
( One way of implementing this would be to write a recursive function that visits every node of the original tree, creates the data attribute for each one, fills up its content by the three attributes att1, att2 and att3, then removes these attributes of the node. This way I would have this new tree. But I don't want to change the original tree, so this is not an option for me. I also don't want to clone the tree using JSON.parse(JSON.stringify()) or in some other way and then perform the same procedure described above for this new tree. )
Instead, I'm looking for a method to generate this new tree node by node, as I'm reading the original tree node by node.
A method I can already write that visits every node of the original tree:
public copyTree(originalTree: Array<object>): Array<object> {
const newTree: Array<object> = [];
function f(subtree: Array<object>): void {
for (const node of subtree) {
// Missing here: Somehow add the current node to newTree
if (node['subs'].length > 0) f(node['subs']);
}
}
f(originalTree);
return newTree;
}
How could I complete this method (or you can show me a different implementation too) to generate the new tree?