javascript - 在 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);
推荐阅读
- php - 在 php 收据上显示条形码
- java - 尝试使用 TO_TIMESTAMP 函数运行本机查询时,Spring JPA 存储库抛出异常
- python - 你会如何在 python 中计算水稻上重叠的谷物?
- swift - 如何在按下按钮时清除 TextField?(迅速)
- ruby-on-rails - 是否可以在基本选择选项上使用 onchange
- flutter - 如何升级现有的 Flutter 应用程序?
- python - 鱼模拟器鱼的生长方式快速和变形。如何修复 Pygame
- python-3.x - 如何解决找不到页面 404 - python django?
- linux - 如何在基于 linux 的服务器上设置 MongoDB
- sql - 如何在where条件中使用if语句编写select语句