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 JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2 Solution

Max Bulygin
Max Bulygin
5,601 Points

Using for..in loop and wrapping properties with different html tags

I just wondering is it possible to get similar result to Dave's solution (when the name of the student is wrapped with <h2> tag and the rest is wrapped in <p>) while using for..in loop like this:

function getStudent( student ) {
  for (key in student) {
    outputHTML += '<p>' + key + ': ' + student[key] + '</p>';
  }
  return outputHTML;
}

In other words, how to access very first key in the loop and apply to it <h2> tag and for the other keys just <p>.

Hopefully my question is clear. Thanks

2 Answers

Hey Max,

Yes, it is possible. here is one way to do it.

function getStudent(student) {
    var outputHTML = "";
    for (var key in student) {
        if(key === "name"){
            outputHTML += '<h1>' + key + ': ' + student[key] + '</h1>';
        } else {
            outputHTML += '<p>' + key + ': ' + student[key] + '</p>';
        }
    }
    return outputHTML;
}

document.write(getStudent({
    name: 'Jordan',
    track: 'PHP Development',
    achievements: '55',
    points: '2025'
}));

Here is a jsFiddle Demo

Max Bulygin
Max Bulygin
5,601 Points

Oh, thanks a lot! It so easy solution that now i'm wondering how couldn't I get it for myself))

Not a problem. sometimes you just need a fresh pair of eyes. I often have the same problem but giving it a break and coming back to it helps you see what you couldn't before.

Glad I could help.