Reputation: 6688
I'm trying to write an .each
statement for objects in a JSON array.
$.ajax({
url: url,
dataType: 'json',
success: function(data){
$.each(data, function (key, value){
...do stuff...
}
});
Problem is, it's only returning one result because it's only doing an .each
for data
when I need it to do an .each
for the objects inside data
. I'm sure it's as simple as .each(data.something ...)
but I can't figure out what it is.
EDIT Per comment request, data looks like:
[["data1","data2","data3"],
["data1","data2","data3"],
["data1","data2","data3"]
]
EDIT2
Here is a JSFiddle of my working code. if I change teh .each
function to just do an alert
it works, but when I try to build divs, it only spits out one entry.
Upvotes: 1
Views: 700
Reputation: 4024
I originally suggested using $.map() to create an array.
But the actual problem was that the OP was overwriting the html in each iteration of the loop. Editing my response to show the actual answer.
Answer: OP needed to change .html() to .append() in his .each() loop.
Upvotes: 1
Reputation: 92903
The problem with your fiddle isn't the .each
loop -- it's that you're using .html()
to add code, which will replace everything inside the specified element with your new code.
Use .append()
instead of .html()
and you should be fine.
Upvotes: 1
Reputation: 4070
Probably it is not a JSON object, just do the following
$.each($.parseJSON(data), function (key, value){
... stuff...
}
depending on the object, you should do a Map:
// Therefore, convert it to a real array
var realArray = $.makeArray( data )
// Now it can be used reliably with $.map()
$.map( realArray, function(val, i) {
// do something
});
Edit - Test on fiddle
With your object we can check that it is a nested array, so you have to double loop on it:
var data = [["data1","data2","data3"],
["data1","data2","data3"],
["data1","data2","data3"]
];
$.each(data, function(key, item) {
$.each(item, function(i, val) {
alert(val);
})
});
Edit 2 - Code for you situation!
$.ajax({
url: url,
dataType: 'json',
success: function(data){
$.each(data, function(key, item) {
$.each(item, function(i, val) {
alert(val);
})
}
}
});
Hope it helps!!
Upvotes: 0
Reputation: 55750
Use one more loop
$.each(data, function(key, value) {
$.each(value, function(i, val) {
console.log(val)
})
})
Upvotes: 0
Reputation: 92903
Sounds like you need a nested loop:
$.ajax({
url: url,
dataType: 'json',
success: function(data){
$.each(data, function (idx1, value1){
$.each(value1, function (idx2, value2){
//...do stuff...
});
});
});
Upvotes: 1