Borislav Hadzhiev
Tue Nov 02 2021·2 min read
Photo by Hanna Postova
To create an object from two arrays, use the forEach()
method to iterate
over the first array. Use the index to access the element from the second array
and assign the key-value pair to an object. After the last iteration, the object
will contain the key-value pairs from the arrays.
const arr1 = ['name', 'age', 'country']; const arr2 = ['Tom', 30, 'Chile']; const obj = {}; arr1.forEach((element, index) => { obj[element] = arr2[index]; }); // 👉️ {name: 'Tom', age: 30, country: 'Chile'} console.log(obj);
The function we passed to the Array.forEach method gets called with each element in the array.
The function gets passed the following 3 parameters:
element
index
of the iterationarray
itselfAfter the method has finished iterating, the object contains the key-value pairs from the two arrays.
An alternative, but more functional approach, is to use the Array.reduce method.
To create an object from two arrays:
reduce()
method to iterate over the first array.const arr1 = ['name', 'age', 'country']; const arr2 = ['Tom', 30, 'Chile']; const obj = arr1.reduce((accumulator, element, index) => { return {...accumulator, [element]: arr2[index]}; }, {}); // 👇️️ {name: 'Tom', age: 30, country: 'Chile'} console.log(obj);
The function we passed to the reduce()
method gets called for each element in
the array.
We've provided an empty object as the initial value for the accumulator
variable.
On each iteration, we use the
spread syntax (...)
to unpack the key-value pairs of the accumulator
into a new object, add the
current key-value pair and return the result.
Once the reduce
method has iterated over the entire array, the accumulator
object will contain the key-value pairs from the two arrays.
forEach
method is more intuitive if you're familiar with the reduce
method.