展平JavaScript对象数组

Jac*_*yan 3 javascript arrays object

我试图展平数组的对象数组。例如,我们可能会有类似的内容:

[{ numbers: [1, 2, 3] }, { numbers: [4, 5] }, { numbers: [6] }]
Run Code Online (Sandbox Code Playgroud)

我想将其展平为:

[1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

我有一个可行的解决方案,像这样:

[{ numbers: [1, 2, 3] }, { numbers: [4, 5] }, { numbers: [6] }]
Run Code Online (Sandbox Code Playgroud)

有谁知道这里更简单或更高效的解决方案,最好没有almostFlattened中间步骤?

Ori*_*ori 6

You can try Array.reduce(), and flatten the numbers' arrays by concatenating the numbers with the accumulator:

const arr = [{ numbers: [1, 2, 3] }, { numbers: [4, 5] }, { numbers: [6] }];

const result = arr.reduce((r, obj) => r.concat(obj.numbers), []);

console.log(result);
Run Code Online (Sandbox Code Playgroud)

Another option is Array.flatMap() (not supported by IE/Edge):

const arr = [{ numbers: [1, 2, 3] }, { numbers: [4, 5] }, { numbers: [6] }];

const result = arr.flatMap(obj => obj.numbers);

console.log(result);
Run Code Online (Sandbox Code Playgroud)


CRi*_*ice 5

为什么不直接使用现有的,而是内联的?almostFlattened当您可以将调用.map作为参数的一部分时,无需声明中间变量.concat

const arr = [{ numbers: [1, 2, 3] }, { numbers: [4, 5] }, { numbers: [6] }]
const result = [].concat(...arr.map(o => o.numbers));
console.log(result)
Run Code Online (Sandbox Code Playgroud)