首页 > 解决方案 > 在 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

标签: javascript

解决方案


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


推荐阅读