Assuming we have the following array structure of n length:
const sourceArray = [
{ "dynamicKey1": true },
{ "dynamicKey2": false },
{ "dynamicKey3": true },
...
]
How could I tersely reduce this array to a single object of dynamic length:
const convertedObj = {
"dynamicKey1": true,
"dynamicKey2": false,
"dynamicKey3": true
...
}
Thanks!
>Solution :
You can achieve this using Array.prototype.reduce() and Object.assign() to merge curr into acc (starts of as {} initially), copying the key-value pairs.:
const sourceArray = [
{ "dynamicKey1": true },
{ "dynamicKey2": false },
{ "dynamicKey3": true }
];
const convertedObj = sourceArray.reduce((acc, curr) => Object.assign(acc, curr), {});
console.log(convertedObj);