Trying to return value from an object array with two same keys to a function. JS Rock paper scissors spock lizard game

Viewed 21

Here's the const that contains the objects array:

const SELECTIONS = [{
    name: 'fire',
    emoji: '',
    beats: 'air',
    beats: 'lizard'
  },
  {
    name: 'water',
    emoji: '',
    beats: 'spock',
    beats: 'fire'

  },
  {
    name: 'air',
    emoji: '',
    beats: 'water',
    beats: 'lizard',
  },
  {
    name: 'lizard',
    emoji: '',
    beats: 'air',
    beats: 'spock',
  },
  {
    name: 'spock',
    emoji: '‍♂️',
    beats: 'fire',
    beats: 'water',
  },
];

Here's the function that returns the winner by comparing the property/key values of player and computer selection

function isWinner(selection, opponentSelection) {
    return selection.beats === opponentSelection.name
}

I added a pair to the object since I have taken a paper, rock and Scissors game and converted it to a paper, rock , Scissors, spock and lizard game.

Or at least I've tried...

I want the function to compare both the 'beats' . I have tried to rewrite the object and the function with no success.

Does anyone have a clue?

1 Answers

Your objects are not going to work as you have them, as you can't have two properties with the same name. i.e. you can't have two beats properties on the same object because the second one will overwrite the first. e.g.

{
  name: 'fire',
  emoji: '',
  beats: 'air',
  beats: 'lizard'
}

Will actually be

{
  name: 'fire',
  emoji: '',
  beats: 'lizard'
}

Because beats is being set to lizard last.

To fix, why not put your beats as an array that way you can easily update your isWinner method to do what you want by using includes to see if the item is included in the beats array.

For example.

const SELECTIONS = [{
    name: 'fire',
    emoji: '',
    beats: ['air', 'lizard']
  },
  {
    name: 'water',
    emoji: '',
    beats: ['spock', 'fire']

  },
  {
    name: 'air',
    emoji: '',
    beats: ['water', 'lizard']
  },
  {
    name: 'lizard',
    emoji: '',
    beats: ['air', 'spock']
  },
  {
    name: 'spock',
    emoji: '',
    beats: ['fire', 'water']
  },
];


function isWinner(selection, opponentSelection) {
  return selection.beats.includes(opponentSelection.name);
}

const fire = SELECTIONS[0];
const lizard = SELECTIONS[3];
const spock = SELECTIONS[4];

console.log(isWinner(fire, lizard)); // true
console.log(isWinner(lizard, fire)); // false
console.log(isWinner(lizard, spock)); // true
console.log(isWinner(spock, fire)); // true 

// etc...

Related