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.

2
  • 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. Commented Oct 1, 2019 at 22:11
  • 1
    Check out stackoverflow.com/questions/684672/… for other ways to do this. Commented Oct 1, 2019 at 22:14

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.