Create an Object from Two Arrays in JavaScript

avatar

Borislav Hadzhiev

Tue Nov 02 20212 min read

banner

Photo by Hanna Postova

Create an Object from Two Arrays #

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.

index.js
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:

  1. The current element
  2. The index of the iteration
  3. The array itself
We made use of the index to access the value from the second array and assigned the key-value pair to an object.

After 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:

  1. Use the reduce() method to iterate over the first array.
  2. Provide an empty object as the initial value for the accumulator.
  3. Using the index, assign the key-value pair to the accumulated object.
  4. Return the result.
index.js
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.

Which approach you pick is a matter of personal preference. Using the forEach method is more intuitive if you're 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