For loops in an object inside an object

Can someone explain why this is not working?

I have two objects inside an object. I use for loops to print each property inside nested objects one by one.

var people = { john: { name: "John", age: 20 }, bob: { name: "Bob", age: 40 } }; for (var person in people) { for (var property in person) { console.log(property); } } 

I expect it to be printed:

 name age name age 

Instead, I get:

 0 1 2 3 0 1 2 

1) What am I doing wrong?

2) What exactly does the console do to display the numbers above?

+4
source share
3 answers

This is because in the second (nested) for loop, you iterate over the person variable strings that contain the property names (not values!) Of the people object. You must change it to people[person] :

 for (var property in people[person]) { console.log(property); } 

The numbers above correspond to the character indices in string values:

 0: j 0: b 1: o 1: o 2: h 2: b 3: n 
+9
source

When you do for..in , you iterate over the keys, not the values.

In for (var person in people) , person is a string; each of the keys: "john" and "bob" .

In your second loop, you iterate over all the properties of this string, which prints the β€œindexes” in the string (you can refer to strings like arrays string[1] ).

You need to get the value of the object before you can iterate over it:

 for (var person in people) { var thisPerson = people[person]; for (var property in thisPerson) { console.log(property); } } 
+2
source

follow as above to print properties, use below to get actual vals

you need to specify a value, not just the index for which it is used. you need to do something like

 for (var person in people) { for (var property in people[person]) { console.log(people[person][property]); } } 
0
source

All Articles