gpt4 book ai didi

javascript - 如何在javascript中合并子数组中的对象,以便在一个数组中留下多个对象

转载 作者:行者123 更新时间:2023-12-03 08:26:22 25 4
gpt4 key购买 nike

我在 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"
}
]

感谢您提前提供的帮助

最佳答案

您可以映射数组并展开对象以获得单个对象。

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

关于javascript - 如何在javascript中合并子数组中的对象,以便在一个数组中留下多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66549530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com