繁体   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