0

I'm learning OOP and am curious to discover why my code isn't looping through all the object instances and logging out the 'firstName' property - check out my demo below:

var people = {
          "person1" : {
              "firstName": "John"
              , "lastName": "Smith"
              , "age" : 25
              , "checkedin" : true
          },
          "person2" : {
              "firstName": "Nick"
              , "lastName": "Debruyne"
              , "age" : 24
              , "checkedin" : false
          }
        }
// console.log(people); // works correctly
for (let person in people) {
  // console.log(person); // works correctly
  console.log(person.firstName); // returns undefined
}

Codepen: https://codepen.io/ns91/pen/VwZoegw?editors=1111

This code should just run through each object instance and log the firstName values of each object (being 'John' and 'Nick'). Is there some rookie error I'm doing here?

Also, why does 'undefined' show in the console? I've noticed this happens for other things I log in the console, and even when successful, it still occasionally occurs. Could someone explain the process of what's going on in the browser here, or why it's showing undefined?

And is this JSON or JS? I wonder if it needs to convert into JS to be readable in JS for loops?

Thanks for any advice here.

user8758206
  • 2,106
  • 4
  • 22
  • 45
  • 1
    Quotes do **not** matter. This is a valid JS object. You just misused the for in loop as mentioned by Jordan in the answers section. – Dragos Strugar Oct 01 '19 at 22:11
  • 1
    Check out https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object for other ways to do this. – Jordan Rieger Oct 01 '19 at 22:14

2 Answers2

3

Your for ... in construct is only giving your loop the keys to each object in the people object, not the values. You need to change the line to console.log(people[person].firstName);.

The reason you were seeing undefined is that you were asking JavaScript to give you the firstName property of the key - which was just the string John or Nick, not the actual person object, and which did not have any such property.

Jordan Rieger
  • 3,025
  • 3
  • 30
  • 50
1

That is going to be because the for(let x in foo) loop iterates over the keys of the object. To access the value you would have to use bracket syntax like so foo[x]. Hope this helps.