jQuery JSON looping through nested objects

前端 未结 2 1183
说谎
说谎 2020-11-29 12:40

I currently have this:

    $.getJSON(\'test.json\', function(data) {
      var items = [];

      $.each(data, function(key, val) {
        items.push(\'<         


        
2条回答
  •  萌比男神i
    2020-11-29 13:21

    so, what you want is a treeview looping through a json object

    you can use this code i made myself recursively, test it ;)

    var treestring      = "";
    var myid            = "arv";
    var json_object     = {your json}; 
    
    var Tree = function (data) {
       this.data = data;
    };
    
    //1st step
    Tree.renderTree(json_object, myid);
    
    //2st step , this is a function
    Tree.renderTree= function (json_object, myid) {
        $.each(json_object, function (key, val) {
            var m = new Tree(val);
            m.render(myid);
        });       
    }
    
    //3st step, this a function too
    Tree.prototype.render = function (myid) {
        treestring = "
  • " + this.data.Name; //Check if has another arrays inside the current if (this.data.SubFolders) { treestring += "
      "; $("#" + myid).append(treestring); myid = this.data.ID; Tree.renderTree(this.data.Sub_Fodlers, myid); } else { treestring += ""; $("#" + myid).append(treestring); } }; //HTML
    • //this.data.{something} ate the fields defined in your json object

      enjoy ;)

    提交回复
    热议问题