Print all paths from root node to leaf nodes - javascript

泪湿孤枕 提交于 2019-12-06 04:24:45

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!