Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Need some help...

So, I have a project in school that I am very confused on. My part is to create a function that lists out the names of the super heroes from this list

var superheroes = [{ Name: "Incredible Hulk", Color: "Green", Superpower: "Strength" }, { Name: "Superman", Color: "Blue", Superpower: "Flying" }, { Name: "Hawkeye", Color: "Purple", Superpower: "Archery" }];

I need to do it in such a way that if more names were added they would also appear in the list. I think using a for loop would be the best way but through all my trial and error I can't figure it out. Any hints/tips?

2 Answers

To list all items with their properties and values , i'd use an for .. in loop, like this

jsfiddle

var superheroes = [
    { 
      Name: "Incredible Hulk", 
      Color: "Green", 
      Superpower: "Strength" 
    }, 
    { 
      Name: "Superman",
      Color: "Blue", 
      Superpower: "Flying"
    }, 
    { 
      Name: "Hawkeye", 
      Color: "Purple", 
      Superpower: "Archery"
    }
];
//loop through all items in object
for (i = 0; i < superheroes.length; i++)
    {
//loop through all properties and their values of those items
            for (var valProp in superheroes[i]) 
        {
//print to console item with 
            console.log(superheroes[i][valProp]);     
        };

    };

As im fairly new to javascript aswell i'd think there are better ways of doing this.

Hope this helps!

Hey. Create a for loop which wil run as long as your index is smaler than the length of the Object. Then, in the body of the loop, use your index to log out the right object. So like this:

console.log(object[index].Name);

I hope this will help you. Happy Coding :)