jQuery looping .each() JSON key/value not working
Solution 1
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
Solution 2
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]);
}
}
passer
Updated on March 25, 2020Comments
-
passer over 4 years
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?