Korey
Korey

Reputation: 89

for loops in object within object

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?

Upvotes: 4

Views: 74

Answers (3)

VisioN
VisioN

Reputation: 145478

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

Upvotes: 9

gen_Eric
gen_Eric

Reputation: 227310

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);
    }
}

Upvotes: 2

Evan
Evan

Reputation: 6115

do as vision says above to print out the properties, use the below to get the actual vals

you need to specify the value instead of just the index which is what for in does. you need to do something like

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

Upvotes: 0

Related Questions