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
source share