jQuery 循环 .each() JSON 键/值不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19969751/
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-08-27 00:51:55  来源:igfitidea点击:

jQuery looping .each() JSON key/value not working

javascriptjqueryjsoneach

提问by passer

I am having problems in looping the key/value of JSON by jQuery .each() function

我在通过 jQuery .each() 函数循环 JSON 的键/值时遇到问题

Initially I have a JSON like this:

最初我有一个这样的 JSON:

json = {"aaa":[
              {"id":"1","data":"aaa1data"}
              ,{"id":"2","data":"aaa2data"}
              ],
        "bbb":[
              {"id":"3","data":"bbb1data"}
              ]
       }

And I would like to loop through all the key/value elements inside the JSON (aaa and bbb) and the retrieve the inner JSON arrays for looping again, so I tried

我想遍历 JSON(aaa 和 bbb)中的所有键/值元素并检索内部 JSON 数组以再次循环,所以我尝试

$(json).each(function(index,data)
{
    var zzz = data;
    $(zzz).each(function(index,data))
    {
       //some other stuff
    }
}

However, I discovered that the first .each() function will regard the whole json as a single structure and will not loop on its element's key.The data parameter received from the .each() function is always the original json itself. I can never get the reference that pointing to the inner JSON array of aaa and bbb.

但是,我发现第一个 .each() 函数会将整个 json 视为单个结构,并且不会在其元素的键上循环。从 .each() 函数接收的数据参数始终是原始 json 本身。我永远无法获得指向 aaa 和 bbb 的内部 JSON 数组的引用。

What would be the problem here and how should I loop for all the key/value elements in a JSON by jQuery properly?

这里有什么问题,我应该如何通过 jQuery 正确循环 JSON 中的所有键/值元素?

回答by Arun P Johny

Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()

由于您有一个对象,而不是 jQuery 包装器,因此您需要使用$.each()的不同变体

$.each(json, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

Demo: Fiddle

演示:小提琴

回答by Jeff Sisson

With a simple JSON object, you don't need jQuery:

使用简单的 JSON 对象,您不需要 jQuery:

for (var i in json) {
   for (var j in json[i]) {
     console.log(json[i][j]);
   }
}