After the first iteration of the each
loop, myArr
is fully loaded with all 4 objects.
(Look in your console for the print out of console.log(myArr)
– after the first loop through).
I am struggling to understand how this is happening, because if you look at the print out of console.log(item)
, it only contains 1 object, not all 4.
So how is myArr
getting fully loaded after the first iteration, when that should only be happening after the 4th iteration?
Here is a link to a JSFiddle with the same code: http://jsfiddle.net/bengrunfeld/fdtom886/
var obj = [
{
"id": 1111,
"todoText": {"index":2,"items":[{"firstName":"Benny"},{"lastName":"Hill"}]}
},
{
"id": 2222,
"todoText": {"index":2,"items":[{"firstName":"Bob"},{"lastName":"Marley"}]}
},
{
"id": 3333,
"todoText": {"index":2,"items":[{"firstName":"John"},{"lastName":"Lennon"}]}
},
{
"id": 4444,
"todoText": {"index":2,"items":[{"firstName":"Led"},{"lastName":"Zeplin"}]}
},
];
var myArr = [];
$.each(obj, function(key, item) {
console.log(myArr);
console.log(item);
myArr.push(item);
});