Sometimes, we want to convert a JavaScript array to object keys.
In this article, we’ll look at how to convert a JavaScript array to object keys.
Convert a JavaScript Array to Object Keys
To convert a JavaScript array to object keys, we can use the JavaScript array’s reduce
method to return an object with the array entries as keys.
To do this, we write:
const arr = ['a', 'b', 'c'];
const res = arr.reduce((acc, curr) => (acc[curr] = '', acc), {});
console.log(res)
We call arr.reduce
with a callback that adds the object keys to the acc
object parameter.
Then we return the acc
object after that.
curr
has the arr
entries that are being iterated through.
And we set each property’s value to an empty string.
The comma operator always returns the last item in the list, so acc
is returned in the callback.
The 2nd argument is an empty object, so we set acc
to an empty object initially.
Therefore, res
is:
{a: "", b: "", c: ""}
Conclusion
To convert a JavaScript array to object keys, we can use the JavaScript array’s reduce
method to return an object with the array entries as keys.