For in... loops + how to iterate through the object within an object

Hi,
I would like to ask about the way, for… in loops work together with objects. In the code below, I understand that “key in mobile” can be either a “property key” or a “property value” - depending in what path we write - so if we write just “key” it shows the ‘property key’, if we write 'mobile[key] it gos further down the path and iterates through the property value:

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

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

If so, and I understand it well:

1. Why I have to use [] and cannot use dot notation to go further down.
2. How can I iterate through the object within and object using for in loop for example in the code below :

let car= {
wheels: 4,
doors: 2,
sound: {
‘accelerating’: ‘brumm’,
‘stopping’: ‘iiii’
}
}

Thanks in advance for your help,
Kamil

Hi Kamil,

If you use dot notation the loop would look for a key named ‘key’ and not replace it with the string assigned to the variable key from your for … in loop.

If you know which key’s values you want to print you could use dot notation:

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

Or you use a nested loop:

for (let key in car) {
 for(let nestedKey in car[key]) {
 	console.log(`${nestedKey}: ${car[key][nestedKey]}`);
 }
}
// "accelerating: brumm"
// "stopping: iiii"
1 Like

Thanks a lot Mirja_T!