-1

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?

  • 1
    `in` iterates over property names. `let role in spaceship.crew` will iterate over the properties of `spaceship.crew`. To then access the values associated with those properties, yes, you'll need `spaceship.crew[role]`. Nothing to do with values being passed by reference. Better approach: `for (const personObject of Object.values(spaceship.crew)) { /* do something with personObject` Or use `Object.entries` to get both the key and value at once – CertainPerformance May 19 '22 at 22:33
  • @CertainPerformance Makes a lot of sense that the `Object` class itself would have a helper function to grab the nested objects themselves. Thank you! – gronk-droid May 19 '22 at 22:39

0 Answers0