简体   繁体   中英

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

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.

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/object-scan@13.7.1"></script>

Disclaimer : I'm the author of object-scan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM