我有一个像这样的数组:
[
{
data: [
{ a: "a", b: "b" },
{ x: "x", y: "y" },
],
},
{
data: [
{ c: "c", d: "d" },
{ z: "z", f: "f" },
],
},
{
data: [
{ d: "d", e: "e" },
{ g: "g", h: "h" },
],
},
];
现在我想将所有项目存储在一个数组中,最终结果是这样的:
[
{ a: "a", b: "b" },
{ x: "x", y: "y" },
{ c: "c", d: "d" },
{ z: "z", f: "f" },
{ d: "d", e: "e" },
{ g: "g", h: "h" },
];
我不想使用我在建议问题中发现的lodash,希望仅使用es6
答案 0 :(得分:1)
只需使用Array.prototype.flatMap,就可以将数据中的所有项目放在一个数组中。
const input = [
{
data: [
{ a: "a", b: "b" },
{ x: "x", y: "y" },
],
},
{
data: [
{ c: "c", d: "d" },
{ z: "z", f: "f" },
],
},
{
data: [
{ d: "d", e: "e" },
{ g: "g", h: "h" },
],
},
];
const output = input.flatMap((item) => item.data);
console.log(output);
答案 1 :(得分:0)
您可能正在寻找:
const params = [
{
data: [
{ a: "a", b: "b" },
{ x: "x", y: "y" },
],
},
{
data: [
{ c: "c", d: "d" },
{ z: "z", f: "f" },
],
},
{
data: [
{ d: "d", e: "e" },
{ g: "g", h: "h" },
],
},
];
const result = params.map(p => p.data).flat();
console.log(result)
答案 2 :(得分:0)
使用数组归约方法。
let a = [
{
data: [
{ a: "a", b: "b" },
{ x: "x", y: "y" },
],
},
{
data: [
{ c: "c", d: "d" },
{ z: "z", f: "f" },
],
},
{
data: [
{ d: "d", e: "e" },
{ g: "g", h: "h" },
],
},
];
let ret = a.reduce((p, c) => p.concat(c.data), []);
console.log(ret);
答案 3 :(得分:0)
let data = [
{
data: [
{ a: "a", b: "b" },
{ x: "x", y: "y" },
],
},
{
data: [
{ c: "c", d: "d" },
{ z: "z", f: "f" },
],
},
{
data: [
{ d: "d", e: "e" },
{ g: "g", h: "h" },
],
},
];
let final =[]
let newData = data.map(el => el.data.map(e => final.push(e)))
console.log(final)
答案 4 :(得分:0)
可与点差运算符一起使用reduce:
const arr = [
{
data: [
{ a: "a", b: "b" },
{ x: "x", y: "y" },
],
},
{
data: [
{ c: "c", d: "d" },
{ z: "z", f: "f" },
],
},
{
data: [
{ d: "d", e: "e" },
{ g: "g", h: "h" },
],
},
];
const newArr = arr.reduce((acc, rec) => [...acc, ...rec.data], [])