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
  • 892
  • 1
  • 8
  • 26
John Wick
  • 387
  • 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
  • 169,008
  • 28
  • 173
  • 236
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71