We have so many loops now in javascript to optimize our code and ignore using old for loop. One such case can be seen in below example.
We have given two array and asked to achieve an object like below
const keys = ["name", "city","gender", "job"];
const values = ["Test User", "Pune", "Female", "Developer"];
Desired Output
{
name:"Test User"
city:"Pune"
gender:"female"
job:"Developer"
}
Using for loop:
const obj = {}
for(let i = 0; i<keys.length; i++){
obj[keys[i]] = values[i]
}
using for in loop:
const obj = {}
for(let i in keys) {
obj[keys[i]] = values[i]
}
using for in loop our code looks more clean and its less complex and more efficient
I hope it will help someone
Top comments (0)