简体   繁体   English

在 js 数组中组合对象而不覆盖它们

[英]Combine Objects in a js array without overwriting them

i have an array like below我有一个像下面这样的数组

 [ { "202229": "8.418" }, { "202229": null }, { "202229": null }, { "202230": "10.713" }, { "202230": "0.859" } ]

i want to convert it to below structure我想把它转换成下面的结构

[ { "202229": "8.418", "202229": null, "202229": null, "202230": "10.713", "202230": "0.859" } ]

Note that values are not overwritten and keys "202229" etc are dynamic.请注意,值不会被覆盖,键"202229"等是动态的。 I tried using reduce methods but i couldn't get it in this format.我尝试使用 reduce 方法,但我无法以这种格式获得它。 Any help would be appreciated.任何帮助,将不胜感激。 Thanks谢谢

You could disperse the keys to various objects.您可以将密钥分散到各种对象。

 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