Convert an Array's Values to Object Keys in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Convert an Array's Values to Object Keys #

To convert an array's values to object keys:

  1. Use the reduce() method to iterate over the array.
  2. On each iteration, assign the array element as a key in the accumulator object.
  3. The reduce method will construct an object from the array's values.
index.js
const arr = ['name', 'age', 'country']; const obj = arr.reduce((accumulator, value) => { return {...accumulator, [value]: ''}; }, {}); console.log(obj); // 👉️ {name: '', age: '', country: ''}
If you don't like using the reduce method, scroll down to the next code snippet.

The function we passed to the Array.reduce method gets called with each element in the array.

We provided an empty object as the initial value for the accumulator variable.

On each iteration, we assign the array value as a key in the object and return the new value of the accumulator variable.

We initialized each key to an empty string, however you can assign whatever value suits your use case.

The object will contain all of the array's elements as keys after the last iteration.

An alternative approach is to use the Array.forEach method.

To convert an array's values to object keys:

  1. Declare a new variable and set it to an empty object.
  2. Use the forEach() method to iterate over the array.
  3. On each iteration, assign the array's element as a key in the object.
index.js
const arr = ['name', 'age', 'country']; const obj = {}; arr.forEach(element => { obj[element] = ''; }); console.log(obj); // 👉️ {name: '', age: '', country: ''}

The function we passed to the forEach() method gets called with each element in the array.

On each iteration, we assign the element as a key in the object.

The final object contains all of the array's elements as keys.

Which approach you pick is a matter of personal preference. Using forEach might be easier to read and more intuitive if you aren't familiar with the reduce method.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.