【问题标题】:Concat an array of arrays(?) or loop over them?连接数组数组(?)或循环它们?
【发布时间】:2020-12-17 16:28:22
【问题描述】:

五月天!我尝试连接数组数组(?)或循环它们,但问题似乎是它们是如何嵌套的,任何关于如何连接这些或一次循环遍历它们的解决方案将不胜感激! 主数组有 5 个索引,但每个索引本身就是一个有 20 个索引的数组。

我刚刚找到了一个关于 flat() 的堆栈帖子,但我仍然无法理解...

这里有更多信息:我从只提供 20 个帖子的 tmdb-API 获取,所以我 loping 5 次向我的状态添加 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))

【问题讨论】:

  • 这是一个对象的数组,而不是数组的数组。请将数据发布为文本而不是图像。还包括您用来循环数组的代码,并描述运行它时会发生什么以及您希望它以不同的方式做些什么。
  • 外部数组的值不是数组,它们是包含数组的对象。你可以做data.flatMap(x => x.results)
  • 是的,但是像 theArray[0].results 这样的下一层应该是一个有 20 个索引的数组?我认为这应该可行,但显然不行: const array1 = loopPosts[0].results.flat(infinity)
  • @visua 如果您想loop 他们,只需使用嵌套的for 循环。 for(let x = 0; x < testing.length; x++) { for(let y = 0; y < testing[x].results.length; y++){ etc.
  • @Code-Apprentice 我现在在我的帖子中添加了一些信息以供澄清。

标签: javascript arrays reactjs multidimensional-array


【解决方案1】:

你有你的数组的例子吗?

myArray = [[1,2],3,[4,5]];

myFlatArray = myArray.flat();

console.log(myFlatArray);

预期的日志结果是 [1,2,3,4,5]

【讨论】:

    【解决方案2】:

    对于展平数组,您可以使用flatMapflat

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 2019-09-11
      • 1970-01-01
      相关资源
      最近更新 更多