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?

1
  • 1
    This has nothing to do with JSON Commented Jul 26, 2014 at 4:10

3 Answers 3

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!
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.