jQuery JSON looping through nested objects

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

I currently have this:

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

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


        
2条回答
  •  Happy的楠姐
    2020-11-29 13:07

    You can make a recursive loop function, but you'd have a problem: when a property is an object, there is no text to display because there is no string. So, you'll end up with:

    - - value11
      - value12
    - value2
    - value3
    

    because while value2 is the string to display for item #2, it is an object that's displayed for item #1.

    Anyway, this is what I made up: http://jsfiddle.net/uXww2/.

    // obj is the object to loop, ul is the ul to append lis to
    function loop(obj, ul) {
        $.each(obj, function(key, val) {
            if(val && typeof val === "object") { // object, call recursively
                var ul2 = $("
      ").appendTo( $("
    • ").appendTo(ul) ); loop(val, ul2); } else { $("
    • ", { id: key }).text(val).appendTo(ul); } }); } $.getJSON('test.json', function(data) { var ul = $("
        "); loop(data, ul); ul.addClass("my-new-list").appendTo('body'); });

提交回复
热议问题