简体   繁体   English

如何在 JavaScript 中解构数组数组?

[英]How can I destructure an array of arrays in JavaScript?

I have an array of arrays.我有一个数组数组。 Each nested array contain objects, however it may contain array of objects.每个嵌套数组都包含对象,但它可能包含对象数组。 For example:例如:

let arr=[[{a:1}],[{b:2}, [{c:3}, {d:4}]]]

I want to create an array which will contain only the objects destructuring all the arrays.我想创建一个只包含解构所有数组的对象的数组。 I tried我试过

arr.reduce((a,b) => [...a,...b], [])

but what am I getting is :但我得到的是:

[{a:1}, {b:2}, [{c:3},{d:4}]]

which is not what I want.这不是我想要的。 I want to get:我想得到:

 [{a:1}, {b:2}, {c:3}, {d:4}]   

You should consider using the Array.flat() method.您应该考虑使用Array.flat()方法。

 console.log( [[{a:1}],[{b:2}, [{c:3}, {d:4}]]].flat() )

You'll notice the above example only flattens one level.你会注意到上面的例子只展平了一层。 This is because the depth parameter defaults to 1 .这是因为depth参数默认为1 In our case, we need to flatten 2 levels, so we explicitly pass 2 to .flat() .在我们的例子中,我们需要展平 2 个级别,因此我们明确地将2传递给.flat()

 console.log( [[{a:1}],[{b:2}, [{c:3}, {d:4}]]].flat(2) )

If you need it to go deeper still, you can increase this number.如果你需要它更深入,你可以增加这个数字。 If you need it to handle any depth, use Infinity .如果您需要它来处理任何深度,请使用Infinity

 console.log( [[{a:1}],[{b:2}, [{c:3}, {d:4}]]].flat(Infinity) )

It is worth noting that as of the writing of this answer, flat() is not supported by all browsers .值得注意的是,在撰写此答案时,并非所有浏览器都支持flat() However, most transpilers (such as Babel) will polyfill it and NodeJS 11+ supports it.但是,大多数转译器(例如 Babel)都会对它进行 polyfill,并且 NodeJS 11+ 支持它。 The MDN documentation for Array.flat() has alternatives that use vanilla Javascript . Array.flat()的 MDN 文档有使用 vanilla Javascript 的替代方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM