-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.

jacob_makau
  • 21
  • 1
  • 4

2 Answers2

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);
}
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
-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);
 }
Zze
  • 18,229
  • 13
  • 85
  • 118