Skip to content Skip to sidebar Skip to footer

How To Get A Random Key Value From A Javascript Object

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 tri

Solution 1:

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!

Post a Comment for "How To Get A Random Key Value From A Javascript Object"