-1

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 winners[userPlay].paper 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?

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
Daneel Rakow
  • 81
  • 1
  • 1
  • 9

1 Answers1

1

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];
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128