-1

I'm trying to call a REST API using for loop and store the output to an array. But the output shows in different arrays for each and every rest API call instead of everything in one array

for each (name in car.cars){

for(i=0; i<count;i++){
    var arr = [];
    var newid = car.cars[i].name;
    var url = "myhost"
    var method = "GET"
var response = "output from REST call"
 arr.push(response)
}
}
karan
  • 65
  • 7

2 Answers2

0

But the output shows in different arrays for each and every rest API call instead of everything in one array

Where is "the output" there's nothing in your code.

Your Problem is that you're declaring the var arr = []; inside your for loop. Initialize the array before the loop starts and just add your responses to that array.

Instead your creating a new array for each iteration of for(i=0; i<count;i++)

Patrick
  • 1,562
  • 1
  • 16
  • 33
0

Take a step back and look at your code again. Where are you declaring your array? Inside the loop.

Next, ask yourself; what is the scope of that array? Only within the loop. Even if just in the outer loop, it won't stick around because as soon as that loop finishes, the array disappears.

Create the array and use it from outside the loops (both of them).

Further reading: Declaring variables inside or outside of a loop

UPDATE 4/30/2019: Thanks to @AuxTaco, I crossed out my inaccurate description of scope in JS. Please see the links in his comment for more reading on this!

cdpautsch
  • 1,769
  • 3
  • 13
  • 24
  • *"What is the scope of that array? Only within the loop."* No. [JavaScript `var`s have functional scope.](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) `arr` is accessible after ([and before!](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)) the loop. – AuxTaco Apr 29 '19 at 23:06
  • Thanks for correcting me! Turns out I am waaay off in my understanding of JavaScript scope. I guess that was my distant Java background bleeding through. – cdpautsch Apr 30 '19 at 15:17