如何在JavaScript中将所有数组值填充到单个索引

时间:2018-12-13 12:29:03

标签: javascript arrays

我有一个在两个索引处都有值的数组,我想将两个索引的值填充到一个可能在不同数组中的索引中。

this.nodesObjResultSingular =  (2) [Array(6), Array(6)]

this.nodesObjResultSingular = [
[
    {sets: Array(1), size: 12},
    {sets: Array(1), size: 12},
    {sets: Array(1), size: 12},
    {sets: Array(2), size: 2},
    {sets: Array(2), size: 2},
    {sets: Array(2), size: 2}
],
[{sets: Array(1), size: 12},
{sets: Array(1), size: 12},
{sets: Array(1), size: 12},
{sets: Array(2), size: 2},
{sets: Array(2), size: 2},
{sets: Array(2), size: 2}]
];

如何获得以下信息?

finalVenn = // all the 12 values of this.nodesObjResultSingular.

2 个答案:

答案 0 :(得分:3)

使用传播运算符连接它们。喜欢:

finalVenn = [...this.nodesObjResultSingular[0], ...this.nodesObjResultSingular[1]]

或者也可以使用Array.concat()

finalVenn = this.nodesObjResultSingular[0].concat(this.nodesObjResultSingular[1])

如果要连接多个索引,请使用:

var multipleArr = [[1], [2, 3], [4, 5, 6 ]]
var res = [].concat.apply([], multipleArr)
console.log(res)

答案 1 :(得分:1)

如果数组的数目未知,则可以将 reduce concat 一起使用:

let data = [
[{sets: Array(1), size: 12},{sets: Array(1), size: 12},{sets: Array(1), size: 12},{sets: Array(2), size: 2},{sets: Array(2), size: 2},{sets: Array(2), size: 2}],
[{sets: Array(1), size: 12},{sets: Array(1), size: 12},{sets: Array(1),size: 12},{sets: Array(2), size: 2},{sets: Array(2), size: 2},{sets: Array(2), size: 2}]];

var merged = data.reduce((acc, arr) => acc.concat(arr), []);
console.log(merged);