How to create an object from two arrays in for loop in JavaScript

In this shot, we’ll learn how to create a JavaScript object from two arrays using a forEach loop.

We’ll start with a problem statement and then look at an example.

Problem

Create a JavaScript object from the given two arrays using a forEach loop.

Example

Input:

arr1 = [1,2,3,4,5]

arr2 = [“apple”, “orange”, “grapes”, “guava”, “watermelon”]

Output:

{ ‘1’: ‘apple’,

‘2’: ‘orange’,

‘3’: ‘grapes’,

‘4’: ‘guava’,

‘5’: ‘watermelon’ }

Solution

We’ll solve this problem using a forEach loop.

//declare two arrays
arr1 = [1,2,3,4,5]
arr2 = ["apple", "orange", "grapes", "guava", "watermelon"]
//create emtpy object
obj = {}
//for each loop
arr1.forEach((ele, i)=>{
obj[ele] = arr2[i]
})
//print the obj
console.log(obj)

Explanation

In the above code snippet,

  • Lines 2 to 3: We declare and initialize two arrays arr1 and arr2.

  • Line 6: We declare an empty JavaScript object.

  • Line 9: We use a forEach loop to iterate through every element where ele represents the elements in the array arr1 and i represents the index.

  • Line 10: We assign keys as elements in the array arr1 and values as elements in the array arr2 to the object obj.

Free Resources