skip to Main Content

Using this code I’m getting a lot of JSON objects inside different arrays:

Image

Code:

for (let i=1; i<=150;i++){
fetch(`A valid URL ${i}`)
  .then(result => result.json())
  .then(result => console.log(result.data.results))
}

How can I combine those arrays into one array?

2

Answers


  1. If you don’t care about the order, you can push the results into another array:

    let allResults = [];
    for (let i=1; i<=150;i++){
    fetch(`A valid URL ${i}`)
      .then(result => result.json())
      .then(result => 
    allResults.push(...result.data.results))
    }
    

    However, you’d need to wait until all the fetch requests are finished, which you can do using async/await and Promise.all:

    let allResults = [];
    const promises = []
    for (let i=1; i<=150;i++){
    promises.push(fetch(`A valid URL ${i}`)
      .then(result => result.json())
      .then(result => 
    allResults.push(...result.data.results)))
    }
    await Promise.all(promises)
    

    If you do care about the order, then you need to return an array from the fetch request like so:

    const promises = []
    for (let i=1; i<=150;i++){
    promises.push(fetch(`A valid URL ${i}`)
      .then(result => result.json())
      .then(result => result.data.results))
    }
    const allResults = (await Promise.all(promises)).flat()
    
    Login or Signup to reply.
  2. You can do it in one line like this:

    const items = Promise.all([...Array(150).keys()].map(i => fetch(`A valid URL ${i}`))).flat()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search