0

I am debugging a web app written in angularjs, I can see that the array contains all the values, but when I begin iterating through the items and want to see the value for each on my watch, it shows as undefined, but I can see the array and the values. It might be the way I am setting the counter?

This is what shows in developer tools in Chrome:

debugging screen

When I select data.[i].Name on item 0, it says that it is undefined, but as you can see on the right, the array contain values.

Can you see where is my error?

Thank you, Erasmo

updated screen shot

undefined key values

1
  • You should loop over data.dataCommentedJun 22, 2020 at 18:30

1 Answer 1

2

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.

8
  • Let me give that a try. Thank you!CommentedJun 22, 2020 at 18:12
  • I can access the array now, just that now I see the keys: Name and Email as undefined. Please see my newest screen shot.CommentedJun 22, 2020 at 18:15
  • none of the options are working. i keep seeing the array with data, but when I attempt to assign the values to the b array, they show as undefined.CommentedJun 22, 2020 at 18:23
  • I am sorry @Bucket, I do not have a lot of experience. How can I show you how item looks?CommentedJun 22, 2020 at 18:26
  • @erasmocarlos Oh, I see why - your data object should actually be data.data. See your first screenshot.
    – Bucket
    CommentedJun 22, 2020 at 18:26

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.