Prateek RG
Prateek RG

Reputation: 13

Javascript : Search hierarchical tree

i have to get child object by name from hierarchical tree in JavaScript

My Sample data is as followed

{
 id: 2, 
 name: "Alphabet",
 parent: null,
 path: "Alphabet", 
 children: [ 
             { id: 3,
               name: "unit3",
               parent: 2,
               path: "Alphabet/unit3",
               children:[ 
                         { id: 5,
                           name: "unit15",
                           parent: 3,
                           path: "Alphabet/unit3/unit15",
                           children:[]
                         }
                       ] 
            },
            {  id: 4,
               name: "unit6",
               parent: 2,
               path: "Alphabet/unit6",
               children: []
            }
          ]
}

I have tried as followed :

getChildFromTree(treeObj,name) : any {

    if(treeObj.name == name) {
      return treeObj;
    }    
    var child;
    for(var i=0;i<treeObj.children.length;i++) {
      if(treeObj.children[i].name == name) {
        child =  treeObj.children[i];                   
        break;
      } else {
        child = this.getChildFromTree(treeObj.children[i],name);
      }
    }
    if(child) {
      return child;
    }   
  }

i am getting undefined when i search "unit15" please let me know, what wrong i am doing here

Upvotes: 0

Views: 701

Answers (2)

vincent
vincent

Reputation: 2181

Not a big fan of re-inveting the wheel and I'd recommend you use a library. We use object-scan for data processing stuff. It's pretty powerful once you wrap your head around it. Here is how you could answer your question:

// const objectScan = require('object-scan');

const find = (haystack, name) => objectScan(['**.name'], {
  rtn: 'parent',
  abort: true,
  filterFn: ({ value }) => value === name
})(haystack);

const data = { id: 2, name: 'Alphabet', parent: null, path: 'Alphabet', children: [{ id: 3, name: 'unit3', parent: 2, path: 'Alphabet/unit3', children: [{ id: 5, name: 'unit15', parent: 3, path: 'Alphabet/unit3/unit15', children: [] }] }, { id: 4, name: 'unit6', parent: 2, path: 'Alphabet/unit6', children: [] }] };

console.log(find(data, 'unit15'));
/* =>
 { id: 5,
   name: 'unit15',
   parent: 3,
   path: 'Alphabet/unit3/unit15',
   children: [] }
*/
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/[email protected]"></script>

Disclaimer: I'm the author of object-scan

Upvotes: 0

leonardfactory
leonardfactory

Reputation: 3501

You are iterating over treeObj.children with for(var i = 0, however even if you find a child when using the recursive function this.getChildFromTree, it will not be returned since for(var i = 0 is not stopped (no break nor return in else branch inside the for loop).

You can simply add a if (child) return child; inside the loop.

Upvotes: 2

Related Questions