![](/img/trans.png)
[英]How to fetch data from the database into a javascript file and store it in array?
[英]How to fetch data from multiple url and store it in single array in javascript?
我有一個對象數組`filteredG`,每個 object 都包含一些關於路線的 Json 數據。 filteredG中的對象可以經常更改。 我要從中獲取的 url 正在根據route.id進行更改。 如果我嘗試 map 這個數據,它不會被映射到單個數組中,因為我試圖從多個鏈接獲取數據。 請注意,路線和停靠點之間存在多對多關系。
我的代碼示例:
filteredG = [{id: 1, attributes: {…}, calendarId: 0, name: 'Rupsha'}, {id: 2, attributes: {…}, calendarId: 0, name: 'Boyra'}]
這個數組有可變長度。
filteredG.forEach((route) => fetch(`/api/stoppages?routeId=${route.id}`)
.then((response) => response.json())
.then((data) => {
data.map((stoppage) => console.log(stoppage));
}));
結果:
此代碼段正在控制台中打印一堆停工對象。
我想要的是存儲這些當前打印在單個數組中的對象。 我怎樣才能做到這一點?
請幫忙。
我希望我明白你的意思
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));
如果你不關心結果進入數組的順序,你可以使用這個選項:
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
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.