FAQ: Objects - Looping Through Objects

Why is [crewMember] appended as “spaceship.crew[crewMember].name”, rather than “spaceship.crew.name[crewMember]”?

I thought that since we are looping through and printing the strings attached to “name” (for example, name: '‘Lily’), we would be appending the array/variable to “name”.

Same question goes for degree. Why “spaceship.crew[crewMember].degree” instead of “spaceship.crew.degree[crewMember]”? We are looping through and printing the degree, not the name of the crew member’s title.

how to loop through array in object, suppose we have following array of objects-

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!’) }
}}
]
};

and we have to get name and degree of each crew member

Is there no inspiration in this topic? We can simply loop over spaceship.crew

Hi. I’m struggling to understand why the syntax below doesn’t work:

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

I was expecting to see

Captain: Lily

etc instead I got:

Captain: undefined

If we console.log crewMember it gives Captain, Chief Officer etc so I assume the variable crewMember is accessing spaceship.crew as per the first line of code in the for...in loop.

So if crewMember is accessing that ‘branch’ of the object can we not just use crewMember.name or [crewMember].name to access each crew member’s name?
Why must we go back and use spaceship.crew[crewMember].name? Are we not repeating ourselves?

Is there no reply in this topic which covers this?

it’s not, for .. in simply gives us a string

Hello,
Please solve one confusion.
Why outside the loop it prints the VALUE. while inside the loop it prints the KEY.

let spaceship = {

crew: {

captain: {

name: ‘Lily’,

degree: ‘Computer Engineering’

}

}

};

//When

console.log(spaceship.crew.captain); //prints the captain key’s VALUE → {name: ‘Lily’, degree: ‘Computer Engineering’} then why

for(let crewMember in spaceship.crew) {

console.log(${crewMember}); //why prints captain (the key its own rather than the value).

}

crewMember is in this case simply a string, namely, the key itself.

1 Like

Thanks a lot. Thanks a lot. Thanks a lot.

1 Like

I like how clean it is when using a variation on your code.

for (x in spaceship.crew) {  
  console.log(`${x}, ${spaceship.crew[x].name}: ${spaceship.crew[x].degree}`)
};
for(i in spaceship.crew){

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

}

As you can see, I didn’t use the let keyword, which makes it a bit like python, but no error reported. Is this OK?

Simple answer, no, it is not okay. It leaks the variable into global scope. Declaration of variables is a big thing in JS, as is protection of block scope and prevention of leakage.

I just tried it. It’s true. It does leak the variable. thanks!

1 Like

I’m confused by this too. Here’s the first code I tried, and I can’t see what’s logically wrong with it -

Why is crewMemb.name insufficient for accessing the name property of each crew member? It logs:
Screen Shot 2022-05-06 at 17.45.35

If the standalone reference to crewMemb retrieves each nested object(seen above), why doesn’t crewMemb.name access the name property inside that same object?

ie. why will spaceship.crew[crewMemb].name be necessary in the second half of that string, when crewMemb alone is seemingly already being read as spaceship.crew[crewMemb] by the program?

Because crewMember is not the object, proper, only the key.

1 Like

Ah brilliant; got tripped up by being so used to reading keys as shorthand for whole properties. Presumed the forest and missed the trees here. Thanks!

1 Like

How do you call the function within the object? I’ve got as far as:

console.log(spaceship.crew.medic.announce());

But I’m getting undefined as well as the message.

But in this lesson, we could do that
https://www.codecademy.com/paths/build-web-apps-with-react/tracks/bwa-javascript-iterators-objects-and-classes/modules/learn-javascript-objects/lessons/objects/exercises/nested-objects

So why can’t we do it here? I’ve got a similar thing, and I’m not seeing why it wouldn’t work

for (const member in spaceship.crew) {
  console.log(`${member}: ${member.name}`)
}
1 Like

the announce method does not return anything, yet when you call this method you also attempt to log the returned result. remove the console.log when calling the announce method

1 Like

I don’t see any for-in loop in the lesson you linked to?

like mtf is saying, using the for-in loop means the iterator (member) in your case is only a string key.

I’m not referring to the for in loop itself, I’m referring to how in the lesson I linked, we are able to chain properties to get nested values. The lesson explanation confirms this

spaceship.nanoelectronics['back-up'].battery; // Returns 'Lithium'


In the preceding code:

* First the computer evaluates `spaceship.nanoelectronics`, which results in an object containing the `back-up` and `computer` objects.
* We accessed the `back-up` object by appending `['back-up']`.
* The `back-up` object has a `battery` property, accessed with `.battery` which returned the value stored there: 'Lithium'

So even if member is a key, we should still be able to access it’s associated value according to the above, that’s my thought process. Let me know where I’m going wrong