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 Objects Loop Through Objects Loop Through an Object's Properties

I've been stuck on task 2 for a while now

const composer = { name: 'Edward Ellington', nickname: 'Duke', genres: ['jazz', 'swing'], instrument: 'piano' };

script.js
const composer = {
  name: 'Edward Ellington',
  nickname: 'Duke',
  genres: ['jazz', 'swing'],
  instrument: 'piano'
};

for ( let prop in composer ) {
  console.log(prop);
  console.log( `${name}: ${composer[prop]}` );
  console.log( `${nickname}: ${composer[prop]}` );
  console.log( `${genres}: ${composer[prop]}` );
  console.log( `${instrument}: ${composer[prop]}` );
}

they created the object 'composer' above and the 'for in' loop was my attempt to log the values of each property, any tips much appreciated! Thank you

3 Answers

Caleb Kemp
Caleb Kemp
12,755 Points

You can see what it is supposed to look like at 4:15 in the video, but here is an additional example for you. Given the following object.

const writers = {
  name: 'Mark Twain',
  nickname: 'Twainster',
  genres: ['Missouri', 'Frontier'],
  instrument: 'Harmonica'
};

If I want to print all the property names for this object I could write

for(let prop in writers){
  console.log(prop);
}

If I want to print all the property values for this object I could write

for(let prop in writers){
  console.log(writers[prop]);
}

This 1 line will print out all the values since this is a "for loop", it will go through every property in the object, we don't need multiple console.log statements.

If I wanted to print all the property names and property values like in the second challenge I could write

for(let prop in writers){
  console.log(prop + ": " + writers[prop] );
}

or

for(let prop in writers){
  console.log('${prop}: ${writers[prop]}' );
}

both are correct

this would give the following output

name: 'Mark Twain'
nickname: 'Twainster'
genres: 'Missouri', 'Frontier'
instrument: 'Harmonica'

I know this is long, but I hope you can see that you only need 1 console.log statement and what format it needs to be in. hope it helps

Oh yes this makes sense thank you!! Appreciate your thorough explanation and example!

can you just put down the answer this making my brain hurt

nevermind