簡體   English   中英

在 js 數組中組合對象而不覆蓋它們

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM