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

Initially I have a JSON like this:

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).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.

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()的不同变体

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

演示:Fiddle

Json相关问答推荐

Vega通孔信号中的动态梯度

按照对象键的值对PostgreSQL JSONB对象进行排序'

Swift解码错误类型与`Bool`type不一致

在Reaction中从JSON文件中筛选数组

VBA json按特定属性名称提取所有数据

解析Ansible AWS ec2_security_group中的json以提取安全组ID

将来自 Golang 的 JSON API 调用响应输出到 nextjs 前端

使用 jq 将消息转换为数组

在 PostgreSQL 中 Select 分层 JSON 作为表

转义 Haskell 记录的字段

如何在 Postman 中匹配 json 响应中的内容?并可视化

如何在 Dart 中与多个 map (字典)相交

Jackson Json:如何将数组转换为 JsonNode 和 ObjectNode?

苗条的 JSON 输出

将json字符反序列化为枚举

如何在 Python 中合并两个 json 字符串?

你如何在 Arrays of Arrays 上 OPENJSON

从 JSON 到 JSONL 的 Python 转换

在播放框架 JsObject 中解析 Json 数组

Backbone.js 模型与集合