Daneel Rakow Daneel Rakow - 4 years ago 80
Javascript Question

How do I get to a certain place in my JavaScript object using variables?

I have a JavaScript object called 'winners' that looks like this:

var winners = {
rock: {
"scissors": true,
"paper": false
paper: {
"rock": true,
"scissors": false
scissors: {
"rock": false,
"paper": true

And I get the users play, as well as the computers play. So to figure out who wins, I need to do something like this:

var userPlay = "rock";
var cpuPlay = "paper"; //this would be a function but for now lets simply it and just set it to "paper"

So to find the value for computing the winner, I need to go something like this:

var winner = winners[userPlay].cpuPlay;

But that always returns undefined. Obviously
works, but I'm not sure how to use a variable to get to that final spot. Do I need to get the value of cpuPlay itself and use that?

Answer Source

Your property name is stored in a variable called cpuPlay.

var cpuPlay = "paper";

To access the property you have to use bracket notation:

var winner = winners[userPlay][cpuPlay];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download