0

I want to use a string as a JSON property in JavaScript.

var knights = {
         'phrases': 'Ni!'
};

var x = 'phrases';

console.log(knights.x);         // Doesn't log "Ni!"

When I run this code, it obviously doesn't work because it interprets "x" and not the contents of the variable "x".

The full code in context on pastebin: http://pastebin.com/bMQJ9EDf

Is there an easy solution to this?

jww
  • 97,681
  • 90
  • 411
  • 885
Will
  • 37
  • 5

3 Answers3

2

Try this to access using variables having string values

kinghts[x]

Basically this is trick

kinghts[x]==knighted["phrases"]==knighted.phrases.

knights.x will get a key named x, So it'll return undefined here.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68
2

knights.x looks for a property named x. You want knights[x], which is equivalent to knights['phrases'] == knights.phrases.

Full code (fixing a couple of typos in your example):

var knights = {
         "phrases": "Ni!"
};

var x = 'phrases';

console.log(knights[x]); // logs Ni!
elixenide
  • 44,308
  • 16
  • 74
  • 100
2

knights.x is the same as knights['x'] - retrieving a property under the key x. It's not accessing the variable x and substituting in the value. Instead, you want knights[x] which is the equivalent of knights['phrases']

MCKapur
  • 9,127
  • 9
  • 58
  • 101