skip to Main Content

I have below spaceship object in JavaScript and then nested objects as well.

js

let spaceship = {
  crew: {
    captain: {
      name: 'Lily'
    },
    'chief officer': {
      name: 'Dan',
    },
    medic: {
      name: 'Clementine',
    },
    translator: {
      name: 'Shauna',
    }
  }
};

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

I am trying to use forin loop but:

displays output as:

captain:undefined
chief officer:undefined
medic:undefined
translator:undefined

Whereas I expect:

captain:Lily
chief Dan
medic:Clementine
translator:Shauna

To achieve the above result, I can do this instead

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

But I am unable to understand why I can’t achieve the same using former code, i.e.

console.log(`${crewMember}:${crewMember.name}`)

2

Answers


  1. In your loop:

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

    crewMember is a string representing the key, such as ‘captain’, ‘chief officer’, etc. Strings do not have a name property, which is why ${crewMember.name} will not give you the desired result.

    To access the name property of the crew member object, you need to use spaceship.crew[crewMember].name, where spaceship.crew[crewMember] accesses the crew member object associated with the current crewMember key in the loop iteration, and .name retrieves the name property of that crew member object. This is why ${spaceship.crew[crewMember].name} works correctly to print out the crew member’s name.

    to achieve what you’re expecting, use the below code.

    for (let role in spaceship.crew) {
            console.log(`${role}: ${spaceship.crew[role].name}`);
        }
    
    Login or Signup to reply.
  2. You’ve mistaken the value and key

    Better naming will help:

    let spaceship = {
      crew: {
        captain: {
          name: 'Lily'
        },
        'chief officer': {
          name: 'Dan',
        },
        medic: {
          name: 'Clementine',
        },
        translator: {
          name: 'Shauna',
        }
      }
    };
    
    for (let crewMemberKey in spaceship.crew) {
      const crewMember = spaceship.crew[crewMemberKey]
      console.log(`${crewMemberKey}:${crewMember.name}`)
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search