jQuery JSON循环遍历嵌套对象 [英] jQuery JSON looping through nested objects

查看:1491
本文介绍了jQuery JSON循环遍历嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有这个:

    $.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如下所示:

test.json looks like this:

{ KEY1:{ key11: value11, KEY12: value12}, KEY2: VALUE2, KEY3: 值3}

我收到:

[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


推荐答案

你可以创建一个递归循环函数,但是你有一个问题:当一个属性是一个对象时,没有要显示的文本,因为没有字符串。所以,你最终得到:

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

因为 value2 是对于项目#2显示的字符串,它是为项目#1显示的对象。

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

无论如何,这是我编写的: http://jsfiddle.net/uXww2/

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');
});

这篇关于jQuery JSON循环遍历嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆