Home > OS >  How to fetch data from multiple url and store it in single array in javascript?
How to fetch data from multiple url and store it in single array in javascript?

Time:11-24

I have an array of Objects `filteredG`, Every single object contains some Json data about route. Objects inside filteredG can change frequently. The url I want to fetch from is changing based on route.id. If I try to map this data it isn't getting mapped inside a single array, since I try to fetch data from multiple link. Note that, there is many to many relations between routes and stoppages.

My code example:

filteredG = [{id: 1, attributes: {…}, calendarId: 0, name: 'Rupsha'}, {id: 2, attributes: {…}, calendarId: 0, name: 'Boyra'}] this array has variable length.

filteredG.forEach((route) => fetch(`/api/stoppages?routeId=${route.id}`)
  .then((response) => response.json())
  .then((data) => {
    data.map((stoppage) => console.log(stoppage));
  }));

Result:

this snippet is printing bunch of stoppages objects in the console.

What I want is to store these objects which is currently get printed in a single array. How can I make that happen?

Please help.

CodePudding user response:

if you don't care about the order in which the results get into the array, you can use this option:

Promise.all(filteredG.map(route =>
  fetch(`/api/stoppages?routeId=${route.id}`)
    .then(response => response.json())
)).then(results => {
   ...here you map the result to an array
})

CodePudding user response:

I hope I understand what you mean

const allData = filteredG.map((route) => fetch(`/api/stoppages?routeId=${route.id}`)
  .then((response) => response.json()));
const aData = Promise.all(allData).then((arrayData) =>
 arrayData.reduce((data, item) => ([...data, ...item]), []));

//result
aData.then(data => console.log(data));
  • Related