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 arraysarr1 = [1,2,3,4,5]arr2 = ["apple", "orange", "grapes", "guava", "watermelon"]//create emtpy objectobj = {}//for each looparr1.forEach((ele, i)=>{obj[ele] = arr2[i]})//print the objconsole.log(obj)
Explanation
In the above code snippet,
-
Lines 2 to 3: We declare and initialize two arrays
arr1andarr2. -
Line 6: We declare an empty JavaScript object.
-
Line 9: We use a
forEachloop to iterate through every element whereelerepresents the elements in the arrayarr1andirepresents the index. -
Line 10: We assign keys as elements in the array
arr1and values as elements in the arrayarr2to the objectobj.