繁体   English   中英

在 es6 中合并嵌套对象的多个嵌套数组?

[英]merge multiple nested array of nested objects in es6?

我有一个这样的数组:

[
  {
    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

简单地说,使用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);

你可能正在寻找这个:

 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)

使用数组减少方法。

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);
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)

可以将 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], [])

暂无
暂无

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

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