1

I have an object x with a bunch of properties. One of the properties is heroes which has the value of array of objects. I am interested in iterating through the array of objects of heroes and accessing specific properties from it.

Here is the code:

x = {id: "prim1", description: "planner", heroes: [{name: "arrow", universe: "dc"}, {name: "shields", universe: "marvel"}]};

I have written a simple for loop to achieve what I wanted as follows:

for (let idx = 0; idx < x.heroes.length; idx++) {
   console.log(x.heroes[idx].universe);
}

How can I implement the same using the latest ES6's for of loop?

Thank you.

1

2 Answers 2

1

Here's the solution using for of loop , you just need to to call the iterable element using this structure:

for (variable of iterable) {
  console.log(variable)
}

On each iteration you can get the current variable.

x = {
  id: "prim1",
  description: "planner",
  heroes: [{
    name: "arrow",
    universe: "dc"
  }, {
    name: "shields",
    universe: "marvel"
  }]
};

for (let idx = 0; idx < x.heroes.length; idx++) {
  console.log(x.heroes[idx].universe);
}

for (let o of x.heroes) {
  console.log(o.universe);
}

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

1 Comment

Thank you Neji :) I wasn't invoking o.universe, instead I was calling x.heroes[o] which was of course returning undefined. A dumb mistake. Thank you again.
0

Try something like with for...of

 var x = {id: "prim1", description: "planner", heroes: [{name: "arrow",  universe: "dc"}, {name: "shields", universe: "marvel"}]};
  
   for (let item of x.heroes) {

     console.log(item.universe); 

   }

2 Comments

the question is how to impement the same loop using the latest ES6's for loop
@Neji , yes I just miss the word ES6's for of loop

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.