Reputation: 1174
I'm trying to create an array of object dynamically using for loop. The values for the key value pair of this object are fed from different arrays. So how can I create the array of object dynamically using for loop? I tried the following block of code but it was not working.
var anObj = [];
var charectors = ['Iron Man', 'Hulk', 'Thor']
var actors = ['Robert Downey, Jr', 'Mark Ruffalo', 'Chris Hemsworth']
for(let i=0; i<charectors.length; i++){
anObj[i] = {
charector : charectors[i],
actor : actors[i]
}
}
The above code throws an error as I was expecting the array of object as
[
{
"charector":"Iron Man",
"actor":"Robert Downey, Jr"
},
{
"charector":"Hulk",
"actor":"Mark Ruffalo"
},
{
"charector":"Thor",
"actor":"Chris Hemsworth"
}
]
Upvotes: 0
Views: 36
Reputation: 25401
You can also use map
var anObj = [];
var charectors = ["Iron Man", "Hulk", "Thor"];
var actors = ["Robert Downey, Jr", "Mark Ruffalo", "Chris Hemsworth"];
const result = actors.map((actor, i) => ({ charector: charectors[i], actor: actors[i] }));
console.log(result)
with for...of loop
var anObj = [];
var charectors = ["Iron Man", "Hulk", "Thor"];
var actors = ["Robert Downey, Jr", "Mark Ruffalo", "Chris Hemsworth"];
const result = [];
for (let [i, actor] of actors.entries()) {
result.push({
charector: charectors[i],
actor: actors[i],
});
}
console.log(result);
Upvotes: 3
Reputation: 148
Use :
instead of =
in your for loop.
Basic object properties assignement
var anObj = [];
var charectors = ['Iron Man', 'Hulk', 'Thor']
var actors = ['Robert Downey, Jr', 'Mark Ruffalo', 'Chris Hemsworth']
for(let i=0; i<charectors.length; i++){
anObj[i] = {
charector : charectors[i],
actor : actors[i]
}
}
Upvotes: 2
Reputation: 7306
You have two errors:
the assignment separator inside the braces is the colon, not the equal sign;
the name of the second source array is actors, not actor.
var anObj = [];
var charectors = ['Iron Man', 'Hulk', 'Thor']
var actors = ['Robert Downey, Jr', 'Mark Ruffalo', 'Chris Hemsworth']
for(let i=0; i<charectors.length; i++){
anObj[i] = {
charector : charectors[i],
actor : actors[i]
}
}
console.log(anObj);
Upvotes: 0
Reputation: 25
Push the values into the array using
anObj.push({
charector: charectors[i],
actor: actor[i]
})
Upvotes: 0