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
jQuery looping .each() JSON key/value not working
提问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
回答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]);
}
}