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?
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.
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".
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.
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
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]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With