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 for
…in
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
In your loop:
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.
You’ve mistaken the value and key
Better naming will help: