Last updated: Mar 4, 2024
Reading timeยท3 min
To convert an array's values to object keys:
reduce()
method to iterate over the array.reduce()
method will construct an object from the array's values.const arr = ['name', 'age', 'country']; const obj = arr.reduce((accumulator, value) => { return {...accumulator, [value]: ''}; }, {}); console.log(obj); // ๐๏ธ {name: '', age: '', country: ''}
The function we passed to the Array.reduce() method gets called with each element in the array.
We used an empty object as the initial value of 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.
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.
Array.forEach
This is a three-step process:
forEach()
method to iterate over the array.const arr = ['name', 'age', 'country']; const obj = {}; arr.forEach(element => { obj[element] = ''; }); console.log(obj); // ๐๏ธ {name: '', age: '', country: ''}
The function we passed to the Array.forEach() method gets called with each element in the array.
On each iteration, we assign the element as a key in the object.
The forEach()
method returns undefined
, so we have to perform some kind of
mutation to persist the state.
The final object contains all of the array's elements as keys.
You can also use a for...of
loop to convert an array's values to object keys.
for...of
This is a three-step process:
for...of
loop to iterate over the array.const arr = ['name', 'age', 'country']; const obj = {}; for (const element of arr) { obj[element] = ''; } console.log(obj); // ๐๏ธ {name: '', age: '', country: ''}
The for...of statement is
used to loop over iterable objects like arrays, strings, Map
, Set
and
NodeList
objects and generators
.
On each iteration, we assign the current array element as a key in the object.
After the last iteration, the object contains all of the array 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.
You can learn more about the related topics by checking out the following tutorials: