我在 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; }
这可以像这样完成,
arr
是你的原始数组-
for (let i = 0; i < arr.length; i++) {
let res = {}, subArr = arr[i];
subArr.forEach((a,ind) => {
Object.assign(res,subArr[0],subArr[1],subArr[2]);
});
arr[i] = res;
}
Nina 给出了最好的答案,但值得注意的是 Object.assign() 是一个浅拷贝。
如果 col 属性本身就是对象,您可以使用如下方法:
const finish = start.map((x) => ({
...x[0],
...x[1],
...x[2]
}));
如果我理解正确的话,...x[0] 语法创建 x[0] 的深层副本,然后我们将其直接分配给新对象,而 Object.assign() 创建浅层副本。