0

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"
  } 
] 

4 Answers 4

3

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);

Sign up to request clarification or add additional context in comments.

2 Comments

This works as it is supposed to be thanks .. selecting as accepted answer
Glad I could help @LalasM
2

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]
   } 
 }

1 Comment

Thanks for the input. In fact that was a typo .. I'm editing it
0

Push the values into the array using


anObj.push({
    charector: charectors[i],
    actor: actor[i]
  })

Comments

0

You have two errors:

  1. the assignment separator inside the braces is the colon, not the equal sign;

  2. 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.