Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loops in object within object

Tags:

javascript

Can someone explain why doesn't this work?

I have two objects within an object. I use for loops to print out each property within the nested objects, one after another.

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 print out:

name
age
name
age

Instead I get:

0
1
2
3
0
1
2

1) What am I doing wrong?

2) What exactly is the console doing to output the numbers above?

like image 517
Korey Avatar asked Dec 20 '22 09:12

Korey


2 Answers

It is because in the second (nested) for loop you iterate string-valued person variables which hold property names (not values!) of people object. You should change it to people[person]:

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

The numbers above correspond to indices of chars in string values:

0: j    0: b
1: o    1: o
2: h    2: b
3: n
like image 110
VisioN Avatar answered Jan 06 '23 12:01

VisioN


When you do a for..in, you are iterating 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 are iterating over all the properties of that string, which prints the "indexes" in the string (you can access strings like arrays string[1]).

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

for (var person in people) {
    var thisPerson = people[person];
    for (var property in thisPerson) { 
        console.log(property);
    }
}
like image 22
Rocket Hazmat Avatar answered Jan 06 '23 13:01

Rocket Hazmat