0

I have an array of objects that I try to iterate over. When I console log that array I can see that it has objects (8) but on next line when I try to iterate over it it goes only in one iteration. Does any one knows what this might be?

console.log(this.options);
console.log(typeof this.options[Symbol.iterator] === 'function');

for (let option of this.options) {
    console.log(option.id);
}

Jerodev
  • 31,061
  • 11
  • 83
  • 102
AlexBor
  • 139
  • 1
  • 11
  • Simple use `for(let i = 0; i < this.options.length; i++) { console.log(this.options[i].id);` – Swoox Dec 08 '17 at 12:38
  • 2
    `console.log` statements are evaluated when you try to expand on them, try `console.log(JSON.stringify(this.options))` instead and share the output. – gurvinder372 Dec 08 '17 at 12:38
  • @swoox, shouldn't be necessary to use your expanded syntax. https://www.typescriptlang.org/docs/handbook/iterators-and-generators.html – isherwood Dec 08 '17 at 12:41
  • @gurvinder372 Ok, now I am confused, it seams that it's one object after all: `[{"id":0,"textTranslationTag":"filter_bets","selected":true,"_requestValue":null,"gameTypes":[1,4],"onlyVideo":false}]` – AlexBor Dec 08 '17 at 12:44
  • 1
    @AlexBor Yes indeed. The other 7 elements are added after your loop. You can also `console.log(this.options.length)` to see that it has only one entry. – Bergi Dec 08 '17 at 12:45
  • @Bergi Does this means that it actually goes 8 times in loop? – AlexBor Dec 08 '17 at 12:47
  • Take a look at https://stackoverflow.com/questions/46213989/iterate-over-array-of-objects-in-typescript – Swoox Dec 08 '17 at 12:47
  • @AlexBor No, it loops a single time. If you were to iterate the same object at the time when you inspected it in the console, it would loop 8 times. Some other code (that you haven't shown us) does change the length of your array – Bergi Dec 08 '17 at 12:49
  • The small *i* block after the console output is there to hover over. You will see the explanation that the value shown is the current value, not the one at the time of execution. At that moment, you had only 1 item in the array. The array has changed since. When you want to log the current result, you can wrap it in `console.log(JSON.parse(JSON.stringify(this.options)));` or some copy function. Or just pause the debugger right after the console.log line. – Jelmer Jellema Dec 08 '17 at 12:50
  • @Bergi Thanks you. – AlexBor Dec 08 '17 at 12:50
  • Read this answer use .map() or foreach() https://stackoverflow.com/a/15751409/7672014 – Swoox Dec 08 '17 at 12:52
  • @Swoox No. The `for of` loop is totally fine and idiomatic. – Bergi Dec 08 '17 at 12:53

0 Answers0