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?
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
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With