JQuery Building List with Json Object

Today i will show how to recursively loop on Json Array of Objects and construct a Tree with “li” and “ul” tags.

So the Tree will look like this in the end:

Item1
   Item2
   Item2-1
   Item2-2
      Item2-2-1
   Item2-3
Item3

Javascript

   var treestring      = "";  
   var myid            = "arv";  
   var json_object     = {your json};   

   var Tree = function (data) {  
     this.data = data;  
   };  

   //USAGE
   Tree.renderTree(json_object, myid);  

   //1st step 
   Tree.renderTree= function (json_object, myid) {  
     $.each(json_object, function (key, val) {  
       var m = new Tree(val);  
       m.render(myid);  
     });      
   }  

   //2st step
   Tree.prototype.render = function (myid) {  
     treestring = "<li class='category'> " + this.data.Name;  
     //Check if has another arrays inside the current  
     if (this.data.SubFolders) {  
       treestring += "<ul id=" + this.data.ID + "</ul>";  
       $("#" + myid).append(treestring);  
       myid = this.data.ID;  
       Tree.renderTree(this.data.Sub_Fodlers, myid);  
     }  
     else {  
       treestring += "</li>";  
       $("#" + myid).append(treestring);  
     }  
   };  

   //HTML  
   <div id="tree">   
      <ul id="arv"></ul>  
   </div>  

- My ID is just for tracking and helps me to build the Tree easily with sense of orientation;
- this.data.Sub_Folders are the Array’s inside of a field;
- this.data.XYZ (XYZ) are the name of the fields
- to use the function just call the USAGE, use it wharever you want, in document ready or in another function
this are the 2 things that you need to count for structure

About these ads

Tags: , , , ,

4 responses to “JQuery Building List with Json Object”

  1. lista de email says :

    great post! i am just starting out in community management marketing media and trying to learn how to do it well – resources like this article are incredibly helpful lista de email lista de email lista de email lista de email lista de email

    • vieiraricardo says :

      that is great, and i think you should do it like that, offcourse you we learn always more and when you look behind you saw that everything can be even better, but is a great start, if you need something else just tell me, thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: