FAQ: Objects - Looping Through Objects

I’m not sure if I follow this explanation. I understand the question. It’s quite abstract. You would think that if console.log({crewMember}`)` references to every member (every element in crew), then digging down 1 level to for example a name of such a member would be `console.log(`{crewMember.name}).

You’re simply digging down from that placeholder/variable crewMember. Doesn’t work though. Anyone can explain why?

crewMember in this example is a variable, so must be subscripted to access it.

spaceship.crew[crewMember].name

Cconsider,


outer = {
  inner: {
    one: {
      name: "One"
    },
    two: {
      name: "Two"
    },
    three: {
      name: "Three"
    }
  }
}
for (let member in outer.inner) {
  console.log(member.name);
  console.log(outer.inner[member].name)
}
undefined
One
undefined
Two
undefined
Three
2 Likes

Thank you. I’m still trying to find the pattern here.

So calling crewMember (an object) you can do directly and calling a value string (crewMember.name) you have to do from the root, describing the entire path?

Or is the difference that you can refer to crewMember because it’s the variable you set in this for in loop and anything other than the variable itself has to have its entire path declared?

Since we are using a variable to hook each inner property, it has to be subscripted (cannot use dot notation). We cannot access only the subscript, so,

[subscript].name

will not work. That means we need the object that it is a subscript of, hence the full identifier.

We could simplify it by creating a stand alone reference…

let crew = spaceship.crew;
for (let member in crew) {
    console.log(crew[member].name);
}

To keep that temporary object from taking up memory, we can clear it by setting it to ‘null’

crew = null;

We could not do this if we declared it with const, hence I used let.