Reduce method is not easy, help me with this problem pls.
i need a function, that receive array with anything, and returns object with fields
{field1, field2, field3, field4}
like in the example: Input:
[true,6,'wow','you are smart, bro']
Output:
{field1: true, field2:1, field3: 'wow', field4: 'you are smart, bro'}
A solution that uses Object.fromEntries (browsers that support ECMAScript 2019 only):
const arr = [true, 6, 'wow', 'you are smart, bro'];
const result = Object.fromEntries(arr.map((x, i) => [`field${i + 1}`, x]));
console.log(result);
A solution that uses Array.prototype.reduce and ECMAScript 2015:
const arr = [true, 6, 'wow', 'you are smart, bro'];
const result = arr.reduce((acc, cur, i) => ({ ...acc, [(`field${i + 1}`)]: cur }), {});
console.log(result);
And a solution that uses Array.prototype.reduce and ECMAScript 5 (browsers as old as IE11):
var arr = [true, 6, 'wow', 'you are smart, bro'];
var result = arr.reduce(function(acc, cur, i) {
acc['field' + (i + 1)] = cur;
return acc;
}, {});
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With