0

If I have the following:

var liststuff = {'key 1':'value 1', 'key 2':'value 2', 'key 3':'value 3'};

How should I go around to get a random key?

So the idea is that I would run a function and it will randomly give me one of the keys from liststuff, which I then could use to do what I want.

I though about giving 2 keys to each value, where the first one would be the 'key n', while the second key would be 'n-1' (n = number of keys):

e.g.

var belonging = {'Tom':'fish', 0:'fish', 'Jerry':'cheese', 1:'cheese', 'Billy':'pencil', 2:'pencil'};

And then I could do the following to get the random key:

let randChoice = Math.floor(3 * Math.random);
belonging[randChoice];

But then it would take too much space as the number of keys increases, and was wondering if there is a different and smarter way of doing this.

Thiranoyama
  • 15
  • 1
  • 5
  • Have a look at [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) – Andreas Jun 22 '19 at 17:56

2 Answers2

1

You can get random index by Math.random * keys.length and then use that index to get a key.

var obj = {'key 1':'value 1', 'key 2':'value 2', 'key 3':'value 3'};

var keys = Object.keys(obj);
var key = keys[Math.floor(Math.random() * keys.length)];
console.log(key)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

Hey you can do it in a simple way using The Object.keys() method which returns an array of a given object's property names.

var items = {'key 1':'value 1', 'key1':'value 2', 'key 3':'value 3'};
const allKeys = Object.keys(items)
const randomValFromItems = items[allKeys[Math.floor(Math.random()*allKeys.length)]];

Hope this helps

TheWizardJS
  • 151
  • 9