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
Reblogged this on Xpress R&D in System Development (IT).
thank you my friend, if you need more info just tell me 🙂
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
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