Print all paths from root node to leaf nodes - jav

2019-05-10 21:57发布

问题:

    function formCategoryTrees(object) {
     _.each(object,function(objectValues){


         var leafCategoryId = objectValues["id"];
         var leafCategoryName =  objectValues["name"];
         console.log(leafCategoryName+""+leafCategoryId );
        if (objectValues.hasOwnProperty("children")) {
            if (typeof objectValues["children"] == 'object')
                 console.log("In");
                formCategoryTrees(objectValues["children"]);
            }else{
console.log(leafCategoryName);
            }

      })

  }

So i want to display the category tree as follows: Mobile & Accessories -> Mobiles

Mobile & Accessories -> Chargers

My JS Fiddle: http://jsfiddle.net/tfa8n5tj/

回答1:

I believe you want your function to look like the following:

function formCategoryTrees(object, parentNode) {

    var div = document.getElementById("output");
     _.each(object,function(objectValues){
         var leafCategoryId = objectValues["id"];
         var leafCategoryName =  objectValues["name"];

         if(parentNode === null){
             div.innerHTML = div.innerHTML + leafCategoryName + " " + leafCategoryId +"</br>";
         } else {
             div.innerHTML = div.innerHTML + parentNode + "->" + leafCategoryName + " " + leafCategoryId + "</br>";
         }

         var hasChildren = objectValues.hasOwnProperty("children");
         var childValue = objectValues["children"];

         if(hasChildren && childValue !== null) {
             formCategoryTrees(objectValues["children"], leafCategoryName);
         }

      });
  }

formCategoryTrees(object.records, null);


回答2:

See http://jsfiddle.net/sjmcpherso/kc9fehyz/ here I've created a hierarchical set of list elements using recursion & iteration. As manipulation of the DOM in loops can greatly affect performance, I have created a virtual DOM and append to the real DOM at the end of the process.

var vDOM = document.createDocumentFragment(); //Create a Document Fragment to store your Virtual DOM
function formCategoryTrees(object,par) { //Use the parent node as a parameter to create hierarchy
   var ul = document.createElement('ul');
   _.each(object,function(objectValues ){       
        var li = document.createElement('li');
        var leafCategoryId = objectValues["id"];
        var leafCategoryName =  objectValues["name"]; 
        li.appendChild(document.createTextNode(leafCategoryName + " " + leafCategoryId));

        if(objectValues["children"]) {      
                formCategoryTrees(objectValues["children"],li);
        }
        ul.appendChild(li);

    })    
    par.appendChild(ul);  //Append to the parent node after each iteration
}
formCategoryTrees(object.records,vDOM);
document.body.appendChild(vDOM); //Append your Virtual DOM to your page