简体   繁体   English

Javascript - 加入对象的 arrays

[英]Javascript - join arrays of objects

I have method in a class that returns 8 arrays with 8 objects each: [{...},{...},{...},{...},{...},{...},{...},{...}] [{...},{...},{...},{...},{...},{...},{...},{...}] etc. the result I would like to get is one array containing all these objects, like this: [{...},{...},{...},{...},{...},{...},{...},{...},{...},{...},{...},{...}] etc. what function should I use to get this?我在 class 中有方法,它返回 8 个 arrays,每个对象有 8 个: [{...},{...},{...},{...},{...},{...},{...},{...}] [{...},{...},{...},{...},{...},{...},{...},{...}] etc.我想要得到的结果是一个包含所有这些对象的数组,如下所示: [{...},{...},{...},{...},{...},{...},{...},{...},{...},{...},{...},{...}]等我应该使用什么 function 来获得这个? I tried with concat() but here I have to pass another array as a parameter...我尝试使用 concat() 但在这里我必须将另一个数组作为参数传递......

Seems to be that .flat() is exactly what you need.似乎.flat()正是您所需要的。

You can use arr.flat(depth);您可以使用arr.flat(depth);

This example is given in the mozilla javascript documentation :此示例在mozilla javascript 文档中给出:

var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

If you are simply trying to merge all the objects into a single array, one way to do this would be to use Array.reduce .如果您只是尝试将所有对象合并到一个数组中,那么一种方法是使用Array.reduce

 const result = [ [{}], [{}], [{}], [{}], [{}], [{}], [{}], [{}] ]; const final = result.reduce( (acc, curr) => { return [...acc, ...curr]; }, []); console.log(final);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Assuming the below as your array of objects structure假设以下作为您的对象结构数组

 let array = [[{name: 1}, {name: 2}, {name: 3}], [{name: 1}, {name: 2}, {name: 3}], [{name: 1}, {name: 2}, {name: 3}]] let out1 = [].concat.apply([], array) console.log(out1)

If you use latest ES then you could try with this array.flat , as mentioned by sirko in the comments如果您使用最新的 ES,那么您可以尝试使用这个array.flat ,正如 sirko 在评论中提到的那样

 let array = [[{name: 1}, {name: 2}, {name: 3}], [{name: 1}, {name: 2}, {name: 3}], [{name: 1}, {name: 2}, {name: 3}]] let out2 = array.flat() console.log(out2)

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

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