Solution
const arr = [true,1,'wow','you are smart, bro']
const f = (acc, rec, index) => {
acc[`field${index + 1}`] = rec //
return acc
}
const result = arr.reduce(f, {})
console.log(result)
Explanation
I extracted the callback function into f variable for readability's sake.
The callback function expects the following input: accumulator acc to store the results in, the value of the current processed element rec, and index.
const f = (acc, rec, index) => {...}
The index is optional but we need to get array indexes anyway to use them in our resulting object's keys. We know that array's index count starts from 0 and not from 1, so we have to add + 1 to the count to get field1 key instead of field0.
I chose to use string interpolation to get the necessary result:
`field${index + 1}`
Then we assign the corresponding array element to the object under the key we've just constructed:
acc[`field${index + 1}`] = rec
The reduce function expects the following input: callback (function f ) and initial value, which here should be an empty object {}, since we need to have an object as result.
reduce(f, {})
Now we create new variable result which will be the output of the reduce function on each element of the array arr:
const result = arr.reduce(f, {})