1

I´m trying to loop an array of objects inside a fetch. Is there a way I can do a loop inside a fetch or make the fetch return the array somehow?

This is what I´ve attempted:

fetch(url)
    .then(response => response.json())
    .then(data => 
        for (i = 0; i < data.length; i++) {
            console.log(data[i])
        })
SCoder20
  • 55
  • 1
  • 6
  • If `data` is an array, then your code will work (though you're missing curly brackets). If it's not, then convert it to an array. `=> {for (...) {...}}` – junvar Feb 14 '22 at 18:35
  • 1
    Does this answer your question? [How do I loop through or enumerate a JavaScript object?](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – Justinas Feb 14 '22 at 18:35
  • Return to what? Fetch handling is a promise, so you can either `await` it (in which case you'll get whatever the last `then` handler returns), or process and _forward_ data to whatever function needs to work with it next by calling that function. – Mike 'Pomax' Kamermans Feb 14 '22 at 18:35
  • You always get a Promise from a `fetch()` (and a `then()` chain). You'll need to learn how to use promises correctly to "return an array". You can also turn your `then`-ey code into `async`/`await`, which is easier to understand. – AKX Feb 14 '22 at 18:35

1 Answers1

3

You need to wrap .then(data) in curly braces

fetch(url)
    .then(response => response.json())
    .then(data => {
        for (i = 0; i < data.length; i++) {
            console.log(data[i])
        }
     })
JaivBhup
  • 792
  • 4
  • 7