Looping through objects

Dear team,

anyone knows why in this loop exercise (https://www.codecademy.com/paths/front-end-engineer-career-path/tracks/fecp-22-javascript-syntax-part-ii/modules/wdcp-22-learn-javascript-syntax-objects/lessons/objects/exercises/for-in) it in the first for…in loop it was okay to set the variable ‘crewMember’ but in the second for…in loop we have to go throught the whole nested object?

Here is the code:


let spaceship = {
crew: {
captain: {
name: ‘Lily’,
degree: ‘Computer Engineering’,
cheerTeam() { console.log(‘You got this!’) }
},
‘chief officer’: {
name: ‘Dan’,
degree: ‘Aerospace Engineering’,
agree() { console.log(‘I agree, captain!’) }
},
medic: {
name: ‘Clementine’,
degree: ‘Physics’,
announce() { console.log(`Jets on!`) } },
translator: {
name: ‘Shauna’,
degree: ‘Conservation Science’,
powerFuel() { console.log(‘The tank is full!’) }
}
}
};

// Write your code below

for (let crewMember in spaceship.crew) {
console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`)
};

for (let crewMember in spaceship.crew) {
console.log(`${spaceship.crew[crewMember].name}: ${spaceship.crew[crewMember].degree}`)
};

It might make it simpler if we assign spaceship.crew to a variable and work with that object…

const crew = spaceship.crew;
for (let member in crew) {  
  console.log(`${member}: ${crew[member].name}`)
}
captain: Lily
chief officer: Dan
medic: Clementine
translator: Shauna
1 Like

The variable ‘member’ means the next object after the object spaceship and the object crew?

member is a key name from the crew object, That means, ‘captain’, ‘chief officer’, ‘medic’ and ‘translator’.

1 Like