Printing all paths from root node to leaf nodes - javascript

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 and accessories → Mobile phones

Mobile devices and accessories → Chargers

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

+3
source share
2 answers

I believe that you want your function to look like this:

 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
source

See http://jsfiddle.net/sjmcpherso/kc9fehyz/ here. I created a hierarchical set of list items using recursion and iteration. Since manipulating DOM in loops can greatly affect performance, I created a virtual DOM and add it 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 
+3
source

Source: https://habr.com/ru/post/1237222/


All Articles