Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 902
passer Avatar asked Nov 14 '13 04:11

passer


People also ask

Can JSON have multiple keys?

No, you cannot. This is a limitation of JSON specification json.org You have to copy you values to each key from the array ["TypeA","TypeB","TypeC"] and store it separately.

Can JSON have multiple keys with same name?

There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used. In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name".

Does key order matter in JSON?

The JSON RFC (RFC 4627) says that order of object members does not matter. Note to future self when Google brings me back here: MongoDB is sensitive to the ordering of keys when checking object equality.


2 Answers

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

like image 169
Arun P Johny Avatar answered Oct 13 '22 12:10

Arun P Johny


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]);
   }
}
like image 11
Jeff Sisson Avatar answered Oct 13 '22 11:10

Jeff Sisson