Javascript如何将两个子数组合并为单个数组

时间:2019-12-04 16:07:11

标签: javascript arrays

我想使数组平坦。

// example of the start array
const myArray = [
  [ 
    { foo: "bar", baz: "qux"},
    { quux: "corge", grault: "garply" }
  ],
  [
    { waldo: "fred", plugh: "xyzzy" },
    { thud: "barbra", streisand: "woohoo" }
  ]
];

但是我希望它是:

// end result
[
  { foo: "bar", baz: "qux"},
  { quux: "corge", grault: "garply" },
  { waldo: "fred", plugh: "xyzzy" },
  { thud: "barbra", streisand: "woohoo" }
]

现在,以下示例给出了结果:(2) [Array(2), Array(2)]

const myArray = [
  [ 
  	{ foo: "bar", baz: "qux"},
    { quux: "corge", grault: "garply" }
  ],
  [
  	{ waldo: "fred", plugh: "xyzzy" },
    { thud: "barbra", streisand: "woohoo" }
  ]
];

let newArray = [];
myArray.forEach((subArray) => newArray.push(subArray));
console.log(newArray);

4 个答案:

答案 0 :(得分:5)

您可以使用Array.flat()展平数组:

const myArray = [
  [ 
    { foo: "bar", baz: "qux"},
    { quux: "corge", grault: "garply" }
  ],
  [
    { waldo: "fred", plugh: "xyzzy" },
    { thud: "barbra", streisand: "woohoo" }
  ]
];

const newArray = myArray.flat();

console.log(newArray);

答案 1 :(得分:1)

您可以使用spread operator来获得想要的东西(但这是一个快速解决方案,有更好的方法来实现):

const myArray = [
  [ 
  	{ foo: "bar", baz: "qux"},
    { quux: "corge", grault: "garply" }
  ],
  [
  	{ waldo: "fred", plugh: "xyzzy" },
    { thud: "barbra", streisand: "woohoo" }
  ]
];

let newArray = [];
myArray.forEach((subArray) => newArray.push(subArray));
newArray = [...newArray[0], ...newArray[1]];
console.log(newArray);

答案 2 :(得分:1)

您可以使用concat合并数组:

const myArray = [
  [ 
    { foo: "bar", baz: "qux"},
    { quux: "corge", grault: "garply" }
  ],
  [
    { waldo: "fred", plugh: "xyzzy" },
    { thud: "barbra", streisand: "woohoo" }
  ]
];

const merged = [].concat.apply([], myArray);
console.log(merged);

答案 3 :(得分:0)

您可以使用Array.concat()

const myArray = [
  [ 
    { foo: "bar", baz: "qux"},
    { quux: "corge", grault: "garply" }
  ],
  [
    { waldo: "fred", plugh: "xyzzy" },
    { thud: "barbra", streisand: "woohoo" }
  ]
];

let newArray = [];
myArray.forEach(
    (subArray) => {
        newArray = newArray.concat(subArray);
    }
);
console.log(newArray);