First of all, the data
object you're iterating over actually contains another attribute called data
, so you need to reference this as data.data
at the start of your loop.
You also need to define the array item in your function callback, then you can reference it without the index i
:
angular.forEach(data.data, function(item) { var b = { Name: item.Name, Email: item.Email }; $scope.arr.push(b); });
I'm leaving i
out for brevity, and because it is not relevant to the operation of your loop. You can of course reintroduce it as you see fit.
By adding this parameter to your function callback, you are telling the iterator, "When I loop through this array called data
, just call each entry item
." This way you don't have to maintain a counter. For a more generic example, these two loops produce the same output:
data = ['a', 'b', 'c']; angular.forEach(['a', 'b', 'c'], function(item) { console.log(item); }); for(var i = 0; i < data.length; i++) { console.log(data[i]); }
You can still get a handle to the current index of your loop as well as the object itself from the function callback:
angular.forEach(data, function(item, index, obj) { console.log("Item " + index + " of " + obj + " is " + item); });
For more information, see the AngularJS API.
data.data