0

I use promises in angular to get some data from the server. In promises success I do

promise.success(function (data, status) {                          
  for (i = 0; i <= data.data.length; i++){
    $scope.anArray[i]  = data.data[i][1] ;
  }   
}                     

I do this because data that came from the server have this structure

{"result":"answered","data":[["jake","508"],["amir","602"],["ben","450"]]}

and I ONLY want to get the numbers 508 , 602 and 450. But I always get the same error TypeError: Cannot read property '0' of undefined reffering to this line : $scope.anArray[i] = data.data[i][0] ;.

Those numbers are feeded to a library to create a chart. Sometimes the chart is created, some times is not. Even if it is created, the same error is always there.

I dont know how to fix that error and getting the chart to be always created without any problems. Looks like the code doesnt like the data.data[i][0] structure, having a simple array like data.data[i] doesnt create an error.

What should I do?

Thanks

3
  • 1
    use angular.forEach() is way cleaner and already in the lib core. docs.angularjs.org/api/ng/function/angular.forEach Commented May 12, 2016 at 16:10
  • @sbaaaang I chose Paarths answer as the right one because it takes the minimum ammount of editing to fix my code. But your suggestion is also very nice, I even forgot there is the forEach. Thanks for the help. Commented May 12, 2016 at 16:21
  • of course you're welcome, just remember angular.forEach() is exactly a for loop cleaner and more easy to use, makes no sense to use plain js when you have that ;) Commented May 15, 2016 at 14:04

1 Answer 1

1

Your for loop has an extra execution. You've initialized i to 0 but you've also used <= which means you are going to execute on array[array.length] which is out of bonds. That returns undefined and when you try to access the [0] index on that undefined you get that error.

Change to

for (i = 0; i < data.data.length; i++){

If you're able to do assignment personally I would go with

$scope.anArray = data.data.map(entry => entry[1]);

and skip the for loop entirely. Note if you want to avoid lambdas this would be

$scope.anArray = data.data.map(function(entry) { return entry[1]; });
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I ment to write $scope.anArray[i] = data.data[i][1] ;, I edited my question, so you can erase that part about 0 from your answer too. Also... DUDE, you are right, all I had to do was to erase the = from my for. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.