Tree traversal with jQuery
<ul id="org" style="display:none"> <li id="visited"><a href="#" class="ui-link">ROOT</a> <ul id="main_child_ul" class="children"> <li><a href="#">Acura</a> <ul> <li><a href="#">Audi</a> <ul> <li><a href="#">BMW</a> <ul> <li><a href="#">Ferrari</a></li> </ul> </li> </ul> </li> </ul> </li> <li><a href="#">Cadillac</a> <ul> <li><a href="#">Acura1</a> <ul> <li><a href="#">Audi1</a></li> </ul> </li> </ul> </li> <li><a href="#">BMW1</a></li> <li><a href="#">Cadillac1</a> <ul> <li><a href="#">Ferrari1</a></li> </ul> </li> </ul> </li> </ul>
This is my html UL LI tree structure.
I want to create the JSON of this tree structure. This list is dynamically generated.
I am using jquery - here is my code - I get help from this article here -
function processOneLi(node) { var aNode = node.children("a:first"); var retVal = { "link": aNode.attr("href"), "title": aNode.text() }; node.find("> .children > li").each(function() { if (!retVal.hasOwnProperty("nodes")) { retVal.nodes = []; } retVal.nodes.push(processOneLi($(this))); }); return retVal; } function json_output() { $("#org > li").each(function() { out.push(processOneLi($(this))); }); console.log("got the following JSON from your HTML:", JSON.stringify(out)); }
This generates json fine only for the smaller tree - I want the solution to be generic. and another problem in this solution is that it repeatedly repeats the same nodes. Please help, I'm stuck in my project.
+4
1 answer
Something like that?
function generateTree($node, result) { result = result || {'nodes' : []}; $node.children('li').each(function(){ var $this = $(this); var anch = $this.children('a').get(0); var elem = { "link": anch.href, "title": anch.innerHTML, "nodes" : [] }; if($this.has('ul')) generateTree($this.children('ul'), elem); result.nodes.push(elem); }); return result.nodes; //or just return result.nodes[0] to access the root as object. But the existing one will be generic in case you are setting up for a class selector for multiple ul as root. }
Call him like
var resTree = generateTree($("#org")); console.log(JSON.stringify(resTree));
+1