FAQ: Objects - Looping Through Objects

Thank you @arendestes for that great tip. Yes, deleting the space after the colon was all it took to receive a pass for question one. Thank you for taking the time to answer my question.

regards.

Hi

Related Topic: Looping using for …in.
The defination on https://developer.mozilla.org/ is giving me headache. Every term used here making me google more and more but no result.

I have question regarding enumerable properties.

Can someone please share some example pointing-out where and what is it.? I tried searching online they keep using the enumerable word or non-enumerable but actually not clearly showing it in example.

Hopefully i can get some help please

thanks
Atif

thankfully, there are some simple explanations:

https://howchoo.com/g/mjblmdmxzgy/enumerable-properties-in-javascript

it is a tricky topic, I have to admit.

I think the most important take away is that enumerable properties show up when we log or loop the object:

const obj = {}

Object.defineProperties(obj, {
    'someProp': {
        value: 'someValue',
        enumerable: true
    },
    'nonEnumerableProp': {
        value: 'someValue',
        enumerable: false
    }
});

console.log(obj);
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key}: ${value}`);
}


console.log(obj.hasOwnProperty('nonEnumerableProp'))

which is why the detection table is so important which is featured in the MDN documentation.

Hi! I am having difficulty understanding how the for… in loop fundamentally works.
Below is the example given on the Learn JavaScript: Objects cheatsheet.

let mobile = {
brand: ‘Samsung’,
model: ‘Galaxy Note 9’
};

for (let key in mobile) {
console.log(${key}: ${mobile[key]});
}

The explanation is stated as thus:

The JavaScript for...in loop can be used to iterate over the keys of an object. In each iteration, one of the properties from the object is assigned to the variable of that loop.

Here is my question or confusion …
so the for ( let key in mobile) assigns the variable ‘key’ to iterate over the properties in the object mobile. Then using ${} syntax, prints the keys through each iteration

console.log(`${key})

// brand
model

So far that makes sense… now I don’t understand how ${mobile[key]} gets the value or strings ‘Samsung’ and ‘Galaxay Note 9’ of each key. I understand dot/ bracket notation is used to access object properties… however currently it seems like the for… in loop is doing the same thing twice?

If the variable ‘key’ is iterating over the keys of the object, shouldn’t printing the key-value pair be written like this?
for (let key in mobile) {
console.log(${key}: ${key[key]});
}
If the condition is already working to have the variable access the keys, why would you need ${mobile[key]} to get the value? The loop already got to the property why do you need to indicate the object again?

I’m sure that this must be an annoyingly basic question but I would really appreciate someone walking through what is actually happening so I can begin the understand what it is I don’t understand. Thank you in advance!

the for .. in loop only gives us the keys. The key is simply a string.

we can then use this string to get the value from the object.

These days, if i needed both the keys and properties i would use entries() method:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

2 Likes

I know that through each iteration of ‘for…in’ crewMember is set to one of spaceship.crew’s keys, but how does JS automatically know which key I am looking for if there is no index? In this example, how does it know that I am looking for their role?

Exercise: https://www.codecademy.com/courses/introduction-to-javascript/lessons/objects/exercises/for-in

Instructions:
Using for...in , iterate through the spaceship.crew object in the code editor and console.log() a list of crew roles and names in the following format: '[crew member's role]: [crew member's name]' , e.g., 'chief officer: Dan' .

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!') } 
        }
    }
}; 
for (let crewMember in spaceship.crew) {
 console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`)
};

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

To access the crew roles we iterate over the crew object. JS has no trouble iterating over keys, it’s what the in operator does, look for keys.

Take a piece of paper and break the whole code into it.
Meanwhile, remembering this will definitely cheer you up (although it might also sober you :unamused:)…

“You are not alone…”

One thing that’s been touched on in the above posts but that I’m still confused about is the use of crewMember -the variable.

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

From my understanding, crewMember is only the name of a variable we assigned with let. Thus, how can we interpolate it with the ${} syntax? It also hasn’t been defined before…

As a follow up, in spaceship.crew[crewMember].name, why is the [crewMember] necessary?

I’m really trying to understand this, and would appreciate your help!

let says something about the scope of the variable.

you define the variable in the loop?

we loop over the different crew members to log the name of each crew member.

Thank you, that makes more sense! But if for only returns strings and not objects… well, isn’t spaceship.crew[crewMember].name an object (it returns the name)? And because

wouldn’t it be better to use .forEach?

Thanks so much again for your help @stetim94!!

we then use this to string to retrieve values from crew object, which are objects

forEach is for array, not object.

Ohhh that clarifies a lot! So, basically for is the only feasible option in this case (compared to while and perhaps other forms of looping)… I see :slight_smile:

I really appreciate your helping me to understand this- it is very clear now, thank you!

Recall that with objects there are two types of notation…

object.property

when there exists a key named property; and,

object[property]

when property is a variable used to reference keys in the object.

We can access a property by its key using the above bracket notation so long as the name is in quotes.

object['property']

When there is whitespace in the key, it must be in quotes and this is the only way to access it (cannot use dot notation).

object['property name']
1 Like

Indeed! And from what I understand, properties will always be keys.

So, just confirming then- between object[property] and object['property'] (with the key name in quotes) the latter is the only correct way to access the value?

Properties will always have keys, and they will have values associated with each one. The key is the name, the key-value pair is the property.

1 Like

Got it now, thank you so much for your help again! :+1: :+1: :+1:

1 Like

Hi , let if I would like to loop under the nested object captain , is it possible with the for…in?

When i tried to do it , i have either some error message or an undefined

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

output :
undefined : undefined
undefined : undefined
undefined : undefined

yes, its possible. but captainDegree is just a string. So you can log each key:

console.log(captainDegree)

if you want to use the key to get the value you can do:

spaceship.crew.captain[captainDegree]

if you just want the name and degree, you don’t need to use a loop

1 Like

Hey y’all! Had a question about step 1 in this process, hoping someone could help.

I was able to eventually figure out the solution thanks to this board, but one part still confuses me: where do we get “role” from?

The solutions here use terms like peoplesRole and crewMemberRole, and I saw the previous reply from @mtf that says “To access the crew roles we iterate over the crew object. JS has no trouble iterating over keys, it’s what the in operator does, look for keys.” That makes sense, but how do WE know to use such terminology? The term “role” isn’t anywhere in the actual code, and it is only mentioned in the first step’s requirements without any guide towards what wording we should use to actually find those roles.

I apologize if this is something obvious and I’m just missing it, I just can’t seem to wrap my head around this.

TL;DR: How do we know to use the term “role” where it appears nowhere in the actual code?