jQuery循环.each()JSON键/值不起作用 [英] jQuery looping .each() JSON key/value not working

查看:127
本文介绍了jQuery循环.each()JSON键/值不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

最初我有这样的JSON:

Initially I have a JSON like this:

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

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

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).each(function(index,data)
{
    var zzz = data;
    $(zzz).each(function(index,data))
    {
       //some other stuff
    }
}

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

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.

这里会出现什么问题以及我应该如何为所有键/值循环jQuery中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包装器,你需要使用另一个 $ .each()的变体

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

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

演示:小提琴

这篇关于jQuery循环.each()JSON键/值不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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