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?

1
  • There is no phrases.keys, there is maybe Object.keys(phrases). Commented Apr 5, 2020 at 12:27

1 Answer 1

5

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!

Sign up to request clarification or add additional context in comments.

Comments