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.
-
Take a look at this. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… You have several options to iterate depending on what you want to doyBrodsky– yBrodsky2018年04月30日 17:04:56 +00:00Commented Apr 30, 2018 at 17:04
2 Answers 2
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);
}
1 Comment
o.universe, instead I was calling x.heroes[o] which was of course returning undefined. A dumb mistake. Thank you again.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
for loop