[英]I have an array of objects and want to combine them into one object IF the one of the keys match (without overwriting the initial properties)
[英]Combine Objects in a js array without overwriting them
我有一個像下面這樣的數組
[ { "202229": "8.418" }, { "202229": null }, { "202229": null }, { "202230": "10.713" }, { "202230": "0.859" } ]
我想把它轉換成下面的結構
[ { "202229": "8.418", "202229": null, "202229": null, "202230": "10.713", "202230": "0.859" } ]
請注意,值不會被覆蓋,鍵"202229"
等是動態的。 我嘗試使用 reduce 方法,但我無法以這種格式獲得它。 任何幫助,將不勝感激。 謝謝
您可以將密鑰分散到各種對象。
const data = [{ 202229: "8.418" }, { 202229: null }, { 202229: null }, { 202230: "10.713" }, { 202230: "0.859" }, { 202231: "0.503" }, { 202231: null }], result = data.reduce((r, o) => { Object.entries(o).forEach(([k, v]) => { let i = 0; while (k in (r[i]??= {})) i++; r[i][k] = v; }); return r; }, []); console.log(result);
.as-console-wrapper { max-height: 100%;important: top; 0 }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.