Convert an Array's Values to Object Keys in JavaScript

avatar

Borislav Hadzhiev

Mon Nov 01 20212 min read

banner

Photo by Annie Spratt

Convert an Array's Values to Object Keys #

To convert an array's values to object keys, call the reduce() method to iterate over the array, passing it an initial value of an empty object. On each iteration assign the array element as a key on the object and return the result.

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've provided an empty object as the initial value for the accumulator variable.

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

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

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

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 on 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 on the object.

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

It's a matter of personal preference which approach you pick. Using forEach might be easier to read and more intuitive if you're not familiar with the reduce method.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee