Is there a way to dynamically create an array of objects using a for loop? I have different arrays with values for the key value pairs of these objects. The code snippet I tried is not producing the expected result.
var characters = ['Iron Man', 'Hulk', 'Thor'];
var actors = ['Robert Downey, Jr', 'Mark Ruffalo', 'Chris Hemsworth'];
var objArray = [];
for(let i=0; i<characters.length; i++){
objArray[i] = {
character: characters[i],
actor: actors[i]
};
}
However, this code is throwing an error and not generating the intended array of objects as shown below:
[
{
"character": "Iron Man",
"actor": "Robert Downey, Jr"
},
{
"character": "Hulk",
"actor": "Mark Ruffalo"
},
{
"character": "Thor",
"actor": "Chris Hemsworth"
}
]