-1

I need some help with accessing the property value of an object that is nested within another object.

I have this code:

 var userStats = {
  'Jacob': {
    visits: 1
  },
  'Owen': {
    visits: 2
  },
  'James': {
    visits: 3,
  },
  'Ann': {
    visits: 4
  }
};

What I want to do is access the value of the visits.

I have tried:

for(var firstName in customerData){
  console.log(firstName.visits);
}

But it is not working. It outputs 'undefined'.

Any help is greatly appreciated.

1
  • 1
    customerData[firstName].visits. Commented Feb 7, 2017 at 11:06

2 Answers 2

3

Where firstName is a string which is the property name(or key) of the object so get object using the string.

for(var firstName in customerData){
  console.log(customerData[firstName].visits);
}

var customerData = {
  'Jacob': {
    visits: 1
  },
  'Owen': {
    visits: 2
  },
  'James': {
    visits: 3,
  },
  'Ann': {
    visits: 4
  }
};


for (var firstName in customerData) {
  console.log(customerData[firstName].visits);
}

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

1 Comment

Or as earthiens call it: A KEY!
-1

I have made customerData an array of objects 'customers' and you can iterate them easily by swapping in for of in the for loop.

for (var customer of customerData)

Example:

 var customerData = [
   {
     firstName: 'Jacob',
     visits: 3
   }, 
   {
     firstName: 'bocaj',
     visits: 2
   }
 ];

 for (var customer of customerData) {
   console.log(customer.firstName, customer.visits);
 }

1 Comment

Thanks everyone for the contribution. I've found Pranav's solution straightforward and working as expected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.