anvw
anvw

Reputation: 149

A better way of dealing with recursive tree nodes nested loops, in PrimeNg

With Tree-and-Node objects, in this case PrimeNg Tree objects (Angular 8) is there a better (more succinct, efficient) way of handling recursive child nodes than this:

for (let treeNode of treeNodes) {
    if (treeNode.children != null) {
        for (let child1 of treeNode.children) {
            // do stuff on children level 1
                if (child1.children != null) {
                    for (let child2 of child1.children) {
                          // do stuff on children level 2
                              if (child2.children != null) {
                                 // etc

ie Is there a way I can avoid a Russian-doll type situation, particularly if I don't know how far deep it goes?

Upvotes: 1

Views: 1501

Answers (1)

Ouroborus
Ouroborus

Reputation: 16894

A recursive function may work depending on if you need to do the same thing at each level:

const processTree = treeNodes => treeNodes.forEach(treeNode => {
  // TODO: process stuff here
  if(treeNode.children != null) processTree(treeNode.children);
});
processTree(treeNodes);

If you really want to use for and such, this would look like:

function processTree(treeNodes) {
  for(let treeNode of treeNodes) {
    // TODO: process stuff here
    if(treeNode.children != null) processTree(treeNode.children);
  }
}
processTree(treeNodes);

Upvotes: 2

Related Questions