首页 > 解决方案 > 如何合并子数组中的对象,以便在javascript中留下一个数组和多个对象

问题描述

我在 ARRAY 1处完整看到了以下数组,我需要每个子数组来合并其中的对象,使其像这样。

数组最终


[
  {"col0":"glasses","col1":"Milky glasses","col2":"292516467012796941"}
  , ...
]

所以最终结果是一个包含 6 个对象的数组。上面的 ... 代表其余的对象。

我已经尝试过[].concat.apply([], array),但它并没有完全达到我想要的效果。我将在 ARRAY 2 的此数组下方发布它的作用

阵列1

[
  [
    {
      "col0": "Glasses"
    },
    {
      "col1": "Milky Glasses"
    },
    {
      "col2": "292516467012796941"
    }
  ],
  [
    {
      "col0": "Knives"
    },
    {
      "col1": "Milky Knives"
    },
    {
      "col2": "292516484536599049"
    }
  ],
  [
    {
      "col0": "Forks"
    },
    {
      "col1": "Milky Forks"
    },
    {
      "col2": "292516497196057096"
    }
  ],
  [
    {
      "col0": "Gloves"
    },
    {
      "col1": "Kewl Gloves"
    },
    {
      "col2": "292534063457108493"
    }
  ],
  [
    {
      "col0": "Wrench"
    },
    {
      "col1": "Kewl Wrench"
    },
    {
      "col2": "292534088244396552"
    }
  ],
  [
    {
      "col0": "Monkey snake"
    },
    {
      "col1": "Kewl Monkey snake"
    },
    {
      "col2": "292534109863936521"
    }
  ]
]

这是我不想要的输出,但到目前为止我能做到的。在 ARRAY FINAL 的顶部查看我想要的输出

阵列 2

[
  {
    "col0": "Glasses"
  },
  {
    "col1": "Milky Glasses"
  },
  {
    "col2": "292516467012796941"
  },
  {
    "col0": "Knives"
  },
  {
    "col1": "Milky Knives"
  },
  {
    "col2": "292516484536599049"
  },
  {
    "col0": "Forks"
  },
  {
    "col1": "Milky Forks"
  },
  {
    "col2": "292516497196057096"
  },
  {
    "col0": "Gloves"
  },
  {
    "col1": "Kewl Gloves"
  },
  {
    "col2": "292534063457108493"
  },
  {
    "col0": "Wrench"
  },
  {
    "col1": "Kewl Wrench"
  },
  {
    "col2": "292534088244396552"
  },
  {
    "col0": "Monkey snake"
  },
  {
    "col1": "Kewl Monkey snake"
  },
  {
    "col2": "292534109863936521"
  }
]

感谢您提前提供任何帮助

标签: javascriptarraysobjectmergeconcatenation

解决方案


您可以映射数组并传播对象以获得单个对象。

const
    data = [[{ col0: "Glasses" }, { col1: "Milky Glasses" }, { col2: 292516467012796900 }], [{ col0: "Knives" }, { col1: "Milky Knives" }, { col2: 292516484536599040 }], [{ col0: "Forks" }, { col1: "Milky Forks" }, { col2: 292516497196057100 }], [{ col0: "Gloves" }, { col1: "Kewl Gloves" }, { col2: 292534063457108500 }], [{ col0: "Wrench" }, { col1: "Kewl Wrench" }, { col2: 292534088244396540 }], [{ col0: "Monkey snake" }, { col1: "Kewl Monkey snake" }, { col2: 292534109863936500 }]],
    result = data.map(a => Object.assign({}, ...a));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读