JSFiddle here: http://jsfiddle.net/xgTt2/3/
I have a $.each nested inside of a $.each, and I’m not sure why the second $.each is running twice. Any ideas?
var serverResponse = [{"Id":"aaa","OrderItems":[{"Id":1,"Description":"Salad"},{"Id":2,"Description":"Pizza"}]},{"Id":"bbb","OrderItems":[{"Id":3,"Description":"Salad"},{"Id":4,"Description":"Pizza"}]}];
$.each(serverResponse, function (index) {
var pos = serverResponse[index];
$('#placeholder').append('<p>' + pos.Id + '</p>')
$.each(pos.OrderItems, function (index) {
$('.orderitem').append('<p>' + this.Id +
' ' + this.Description + '</p>')
});
});
The above javascript is producing the following output:
aaa
1 Salad
2 Pizza
3 Salad
4 Pizza
bbb
3 Salad
4 Pizza
I want this:
aaa
1 Salad
2 Pizza
bbb
3 Salad
4 Pizza
Any idea what I’m doing wrong? Here’s a working example of the problem: http://jsfiddle.net/xgTt2/3/
Near the end, you have two elements with the class
orderitem. Using$('.orderitem').append()will append to both of them.Instead, you want to append to the last element you created.
http://jsfiddle.net/xgTt2/4/