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. I tried using reduce methods but i couldn't get it in this format. 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 }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.