[英]Merge multiple arrays of objects into one array of objects JavaScript
[英]How to merge objects in a subArray such that there is one array left with multiple objects in javascript
我在 ARRAY 1處完整看到了以下數組,我需要每個子數組來合並其中的對象,使其像這樣。
數組最終
[
{"col0":"glasses","col1":"Milky glasses","col2":"292516467012796941"}
, ...
]
所以最終結果是一個包含 6 個對象的數組。 上面的...代表對象的rest。
我已經嘗試過[].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"
}
]
]
這是我不想要的 output,但到目前為止我能做到的。 請參閱我想要的 output 在 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"
}
]
感謝您提前提供任何幫助
您可以 map 數組並傳播對象以獲得單個 object。
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,而 Object.assign() 創建淺層副本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.