0
var animals = {DOGS: 10, CATS: 1, RATS: 20, COWS: 0};

console.log(animals.DOGS); //output is 10

Very simple - I can access the value of DOGS by referencing it directly.

However I want to use a dynamic variable like the following:

var dynamicaccess = "CATS";

console.log(animals.dynamicaccess); //output is undefined

How come I am getting undefined? To a noob like me this seems really straightforward and should work! I've googled and there's not much reference to this, as apparently it should work! (Tried the code using Firefox and using jsfiddle)

mdgsec
  • 83
  • 1
  • 13

1 Answers1

2

Use the bracket notation - animals[dynamicaccess]

Demo

var animals = {DOGS: 10, CATS: 1, RATS: 20, COWS: 0},
    dynamicaccess = "CATS"

console.log(animals.DOGS);
console.log(animals[dynamicaccess]);
Kristianmitk
  • 4,528
  • 5
  • 26
  • 46
  • 1
    There are hundreds of duplicate answers for this situation – charlietfl Apr 22 '18 at 11:29
  • @charlietfl my withering excuse is I used google rather than the tools within stackoverflow. Honestly google was giving me dot notation a lot!! But you're right, apologies. – mdgsec Apr 22 '18 at 11:41
  • 1
    actually I prefer google as the SO search is horrible.... this search is good for the topic https://www.google.com/search?q=javascript+object+variable+property+&ie=utf-8&oe=utf-8&client=firefox-b-1 – charlietfl Apr 22 '18 at 11:42
  • yeah I usually do depend on google but in this case SO did flag the duplicates. In any case bad form by me. One of those moments you need to walk away for a bit! – mdgsec Apr 22 '18 at 11:43
  • @charlietfl thats true, so answering the question is *wrong*? Just marking as duplicate? – Kristianmitk Apr 22 '18 at 11:52
  • regarding searching: I can recommend duckduckgo. Shows directly the accepted answer on SO - https://duckduckgo.com/?q=javascript+object+variable+property&atb=v100-7&ia=qa – Kristianmitk Apr 22 '18 at 11:53