0

I have a Javascript hash of Spanish words/phrases and their English meanings:

  let phrases = {
    hola: "hello",
    adios: "bye",
  };

I want to select a random key. I have tried for a while, and my latest attempt hasn't worked and returns undefined:

  var keys = phrases.keys;
  var len = phrases.length;
  var rnd = Math.floor(Math.random()*len);
  var key = phrases[rnd];

I've looked at other Stack Overflow answers but can't seem to find exactly what I'm looking for. Any ideas please?

norbitrial
  • 14,716
  • 7
  • 32
  • 59
juemura7
  • 411
  • 9
  • 20

1 Answers1

3

Probably you can use Object.keys() instead.

Try the following:

const phrases = {
  hola: "hello",
  adios: "bye",
};

const keys = Object.keys(phrases);
const len = keys.length;
const rnd = Math.floor(Math.random() * len);
const key = phrases[keys[rnd]];

console.log(key);

I hope this helps!

norbitrial
  • 14,716
  • 7
  • 32
  • 59