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.
Create a JavaScript object from the given two arrays using a forEach
loop.
Input:
arr1 = [1,2,3,4,5]
arr2 = [“apple”, “orange”, “grapes”, “guava”, “watermelon”]
Output:
{ ‘1’: ‘apple’,
‘2’: ‘orange’,
‘3’: ‘grapes’,
‘4’: ‘guava’,
‘5’: ‘watermelon’ }
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)
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
.