I have an array of key-value pairs:
const arr = [
{ key: 'One', value: '1' },
{ key: 'Two', value: '2' },
{ key: 'Three', value: '3' }
];
I would like to convert the above array into this kind of object:
const obj = {
'One': '1',
'Two': '2',
'Three': '3'
}
by using the Array.reduce()
function.
This is what have I done so far:
const obj = arr.reduce( (prev, curr) => prev[curr.key] = curr.value, {} );
which is not working because, on the second run of the reduce
function, prev
is undefined and therefore I get this error:
ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'Two' of undefined
I thought I would be able to compose obj
at each reduce
iteration...
What am I doing wrong?