0

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.

2
  • Can you add more informations about what is stoppage ? Commented Nov 24, 2022 at 5:45
  • @superdunck Stoppage are array of objects like routes. Commented Nov 24, 2022 at 9:23

2 Answers 2

1

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

1 Comment

Objects are getting repeated inside the array. Not showing the correct result. Even if route.id get changed, it's showing all objects inside the array
0

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
})

1 Comment

It is storing data in a single array. But the result doesn't change when route.id get changes. result expected to be shown only for the selected route.

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.