javascript 当对象值是使用 jQuery 的对象数组时遍历 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5902560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:45:10  来源:igfitidea点击:

traverse JSON when object value is an array of objects with jQuery

javascriptjqueryjson

提问by tomwolber

Here is my external JSON:

这是我的外部 JSON:

{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 3}, "objects": [{"body": "this is copy text", "id": "1", "pub_date": "2011-05-04T12:23:26", "resource_uri": "/api/v1/entry/1/", "slug": "test-title-number-one", "title": "test title number one", "user": "/api/v1/user/1/"}, {"body": "this is the second test text", "id": "2", "pub_date": "2011-05-04T15:01:16", "resource_uri": "/api/v1/entry/2/", "slug": "second-test", "title": "Second test", "user": "/api/v1/user/1/"}, {"body": "item three", "id": "3", "pub_date": "2011-05-05T12:04:04", "resource_uri": "/api/v1/entry/3/", "slug": "item-3", "title": "item 3", "user": "/api/v1/user/1/"}]}

Here is my JS:

这是我的JS:

$.ajax({url: "/api/v1/entry/?format=json", 
dataType: "json",
success: function(json) {
    $.each(json.objects[0], function(key, value) { 
      alert(key + ': ' + value); 
    });
}
});

I can index the objects in the array with $.each(json.objects[0]..., but I need to be able to hit each object in the array and I don't know why simply $.each(json.objects... doesn't work. Thanks!

我可以用 $.each(json.objects[0]... 索引数组中的对象,但我需要能够命中数组中的每个对象,我不知道为什么只是 $.each(json.对象...不起作用。谢谢!

回答by Chad

Just do a normal JS loop:

只需做一个普通的 JS 循环:

for(var i = 0; i < json.objects.length; ++i)
{
   $.each(json.objects[i], function(key, value) { 
      alert(key + ': ' + value); 
    });
}

回答by Jeremy Battle

For a full jQuery solution you can do:

对于完整的 jQuery 解决方案,您可以执行以下操作:

$.each(json.objects, function(key, value) {
    $.each(json.objects[key], function(key, value){
        alert(key + ': ' + value);
    })
});

jsfiddle demo: http://jsfiddle.net/LGC9X/beware, lots of alerts :P

jsfiddle 演示:http: //jsfiddle.net/LGC9X/当心,很多警报:P