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])
        })
4
  • 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 (...) {...}} Commented Feb 14, 2022 at 18:35
  • 1
    Does this answer your question? How do I loop through or enumerate a JavaScript object? Commented Feb 14, 2022 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. Commented Feb 14, 2022 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. Commented Feb 14, 2022 at 18:35

1 Answer 1

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])
        }
     })
Sign up to request clarification or add additional context in comments.

Comments

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.