As I work with a flat one-dimensional array of type TreeNode (view interface definition below), my goal is to recursively traverse the array and add subsequent array elements as children.
While attempting a non-recursive approach using a buffer, I encountered an issue when trying to handle
node.children[0].children[0]...children[0]
since each parent has only one child.
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 will be a nested TreeNode object, structured 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 am seeking a method to dynamically access treeNode1.children[0].children[0]......children[0] in a loop for X number of children to assign to the next level of children in treeNode1.