-1

I am trying to access the array value of a certain person property, but instead it is giving me the index of the string person. How do I fix this to get the desired output?

var Stats = {  
  person1: [17, 0],   
  person2: [15, 0],  
  person3: [10, 2],  
  person4: [7, 5],  
  person5: [5, 7]  
};  

for (var key in Stats) {
  if(key === person4){
    console.log(key); //Output "Person4" as expected
    console.log(key[0]); //Output "P" when I expect/want 7
  }
}

Andrew Whitaker
  • 121,982
  • 31
  • 284
  • 303
rsiemens
  • 597
  • 8
  • 15

1 Answers1

3

You want:

Stats[key][0]

instead.

Stats[key] will give you the array associated with the key person1. Then you can access the array by index.

For a good article on JavaScript objects, check out MDN's Working with objects article.

Andrew Whitaker
  • 121,982
  • 31
  • 284
  • 303