Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

javascript - jQuery JSON looping through nested objects

I currently have this:

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

      $.each(data, function(key, val) {
        items.push('<li id="' + key + '">' + val + '</li>');
      });

      $('<ul/>', {
        'class': 'my-new-list',
        html: items.join('')
      }).appendTo('body');
    });

test.json looks like this:

{"key1":{"key11":"value11","key12":"value12"},"key2":"value2","key3":"value3"}

I'm getting:

[object Object]
value2
value3

How can I change it so it will loop through all the nested items regardless of how many nested values I have?

So for the above example I will get

value1
    value11
    value12
value2
value3
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = $("<ul>").appendTo(
                $("<li>").appendTo(ul)
            );

            loop(val, ul2);
        } else {
            $("<li>", {
                id: key
            }).text(val).appendTo(ul);
        }
    });
}

$.getJSON('test.json', function(data) {
  var ul = $("<ul>");

  loop(data, ul);

  ul.addClass("my-new-list").appendTo('body');
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...