Donut
Donut

Reputation: 185

Iterating an array of objects using for of loop in javascript

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.

Upvotes: 1

Views: 79

Answers (2)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

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

   }

Upvotes: 0

Neji Soltani
Neji Soltani

Reputation: 1511

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

Upvotes: 1

Related Questions