I recently took the dive into JavaScript, and while learning on codecademy about Embedded Objects, the task given was to print out some info from this object:
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!') }
}
}
};
It asked me to print out a list formatted as:
[crew member's role]: [crew member's name]
So, I made a for..in loop as such:
for (let role in spaceship.crew) {
console.log(`${role}: ${role.name}`)
}
This did not work. Which led me to ask: If objects are passed by reference, wouldn't the role be a reference to the objects nested inside of spaceship.crew? Why do I have to write this?
for (let role in spaceship.crew) {
console.log(`${role}: ${spaceship.crew[role].name}`)
}
Furthermore, this gets even more messy when it wanted me to print out the name and degree of each nested object, resulting in something I find to be much less readable than what I presumed to be correct:
for (let role in spaceship.crew) {
console.log(`${spaceship.crew[role].name}: ${spaceship.crew[role].degree}`)
}
Instead of simply:
for (let role in spaceship.crew) {
console.log(`${role.name}: ${role.degree}`)
}
I know I am really new to learning the ins and outs of JS, but in the case I am working with larger objects that have multiple nested objects, this could be a much harder piece of code to read than I feel like it should be. Does anyone know why this is the behavior that results?