1

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?

anvw
  • 149
  • 3
  • 15
  • Usually, if you have a recursive structure, you use recursive functions to handle it. This works so long as the work to do is the same for each tier. – Ouroborus Nov 19 '20 at 05:17
  • Sorry - maybe I'm not getting what you are saying. I can't just do for (var i = 0; i < numberOfTiers; i++) { /* do stuff on tier */ } --because each tier exists *within* the parent tier -- I can't just loop over tiers successively. – anvw Nov 19 '20 at 05:34

1 Answers1

1

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);

Ouroborus
  • 16,237
  • 4
  • 39
  • 62