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

passer picture passer · Nov 14, 2013 · Viewed 150.2k times · Source

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

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?

Answer

Arun P Johny picture Arun P Johny · Nov 14, 2013

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

Demo: Fiddle