[英]Concat an array of arrays(?) or loop over them?
勞動節? 我試圖連接一個數組數組(,)或循環它們,但問題似乎是它們是如何嵌套的,任何關於如何在一個 go 中連接這些或循環它們的解決方案將不勝感激。 主數組有 5 個索引,但每個索引本身就是一個有 20 個索引的數組。
我剛剛找到了一個關於 flat() 的堆棧帖子,但我仍然沒有得到它...
這里有更多信息:我從只提供 20 個帖子的 tmdb-API 獲取,所以我 loping 5 次向我的 state 添加 100 個帖子。 但結果是一個凌亂的嵌套事物,我想將其展平為一個干凈的數組:
const fetchLoop = async(page)=> {
const URL = `https://api.themoviedb.org/3/movie/${type}?
api_key=${API_KEY}&language=en-US&page=${page}`
const fetchRes = await fetch(URL)
.then(res => res.json())
setLoopPosts(prev => [...prev, fetchRes])
}
[1,2,3,4,5].forEach(page => fetchLoop(page))
你有你的 arrays 的例子嗎?
myArray = [[1,2],3,[4,5]];
myFlatArray = myArray.flat();
console.log(myFlatArray);
預期的日志結果是 [1,2,3,4,5]
對於展平 arrays,您可以使用flatMap
或flat
。
const data = [ { page: 1, results: [{ a: 1 }] }, { page: 2, results: [{ b: 2 }] }, ]; // Using flatMap const res = data.flatMap((item) => item.results); console.log(res); // Using flatMap and destructuring const res2 = data.flatMap(({results}) => results); console.log(res2); // Using map, destructuring and flat const res3 = data.map(({results}) => results).flat(); console.log(res3);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.