2

Im trying to use a JavaScript object reference to dynamically call different values of an array. Here is tje code i have

//A static call to the object that works and retutns a value
var sam = (obj.Matt); 
console.log(sam)

However, if i do something like this, I am returned an undefined variable from the console log. Theoretically, the variable trent will change based on key in array.

//A dynamic reference
var trent = "Matt";
var sam = obj.trent
Mrigank Pawagi
  • 802
  • 1
  • 8
  • 24
John Wick
  • 377
  • 1
  • 2
  • 8

1 Answers1

5

Change this:

var sam = obj.trent   // "dot notation"

to this:

var sam = obj[trent]; // array index notation

Because variables can't be used in standard "dot notation", but they can be used to pass a string into an object and look up the property (key) with that string name.

mplungjan
  • 155,085
  • 27
  • 166
  • 222
Scott Marcus
  • 60,351
  • 6
  • 44
  • 64