0

Let's say I have this object:

const people = {
     frodo: { name: 'Frodo', age: 33 },
     aragorn: { name: 'Aragorn', age: 87 },
     legolas: { name: 'Legolas', age: 2931 }
}

And let's say I want to loop over the properties of that object, like this:

for (var person in people) {
    console.log(person.name);
}

I get undefined for any property of the person I tried to access. Why does this happen, and what's the correct way to loop the properties of that object and still be able to access their own properties?

Andrio
  • 1,852
  • 2
  • 25
  • 54

4 Answers4

2

The for ... in loop iterates over the keys (properties) of an object. So

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

will get you the desired result.

The variable person will receive the values "frodo", "aragorn" and "legolas" during the execution of the loop which are the keys (properties) of your person object.

2

You take the keys of the object with for ... in statement. Then you need it as property accessor fopr the object.

const people = {
     frodo: { name: 'Frodo', age: 33 },
     aragorn: { name: 'Aragorn', age: 87 },
     legolas: { name: 'Legolas', age: 2931 }
}

for (var person in people) {
    console.log(people[person].name);
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You need to look at what person is within your code:

const people = {
     frodo: { name: 'Frodo', age: 33 },
     aragorn: { name: 'Aragorn', age: 87 },
     legolas: { name: 'Legolas', age: 2931 }
}

for(person in people) console.log(person);

It's the name of the object, not the object itself. To access it you need to specify where the object is located:

  const people = {
         frodo: { name: 'Frodo', age: 33 },
         aragorn: { name: 'Aragorn', age: 87 },
         legolas: { name: 'Legolas', age: 2931 }
    }

    for(person in people) {
      console.log( people[person].age, people[person].name, people[person] );
    }
zfrisch
  • 8,474
  • 1
  • 22
  • 34
1

for .. in returns every key in the object. You can get the person by using the key.

const people = {
     frodo: { name: 'Frodo', age: 33 },
     aragorn: { name: 'Aragorn', age: 87 },
     legolas: { name: 'Legolas', age: 2931 }
}

for(var key in people) {
    var person = people[key]
    console.log(person.name)
}
frithjof
  • 345
  • 3
  • 8