Given a flat one dimensional array of type TreeNode (see interface definition below), I would like to traverse the array and add subsequent array elements as children.
Would be great to do recursively, my shot at non-recursion uses a buffer, but the issue I am facing is how to do node.children[0].children[0]...children[0] as notice that there is only one child per parent.
Childify(results: TreeNode[]): any {
var node: TreeNode;
var buffer: TreeNode;
var count: number = 0;
for (var res of results) {
if (count == 0) {
node = res[0];
buffer = res[0];
buffer.children = [];
node.children = [];
} else if (count == 1) {
buffer.children = res[0];
} else {
node = buffer;
node.children = [];
node.children.push(res[0]);
buffer = <TreeNode>node.children;
}
count++;
}
}
Interface definition:
export interface TreeNode {
label?: string;
data?: any;
icon?: any;
expandedIcon?: any;
collapsedIcon?: any;
children?: TreeNode[]; <---------------
leaf?: boolean;
expanded?: boolean;
type?: string;
parent?: TreeNode;
partialSelected?: boolean;
styleClass?: string;
draggable?: boolean;
droppable?: boolean;
selectable?: boolean;
}
The input:
TreeNode[] = [treeNode1, treeNode2, treeNode3, treeNode4,...,treeNodeX]
The output is a TreeNode object, nested by the children property (which is also of TreeNode type):
TreeNode = treeNode1
treeNode1.children = treeNode2
treeNode2.children = treeNode3
treeNode3.children = treeNode4
treeNodeX-1.children = treeNodeX
I don't know how to envoke treeNode1.children[0].children[0]......children[0] dynamically for X number of children in a loop, to assign to the next level of children in treeNode1.