33

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?

passer
  • 634
  • 2
  • 8
  • 16

2 Answers2

72

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

DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • It works! Thanks for your reply with explanation since I did not know $.each() and $(selector).each() are not the working in the same way :). – passer Nov 14 '13 at 05:09
  • @Arun p Johny - `console.log('index', data)` here data is parameter or array index, got confuse with the word data, if i want only second value, how can i get? without id? – 151291 Dec 23 '15 at 09:15
  • my json is `{ "0":{"tech_id":"35","tech_name":"Ajax"}, "1":{"tech_id":"36","tech_name":"Ajax"} }` – 151291 Dec 23 '15 at 09:38
11

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

for (var i in json) {
   for (var j in json[i]) {
     console.log(json[i][j]);
   }
}
Jeff Sisson
  • 1,616
  • 11
  • 22