2

Can anyone tell me how to select a random key and corresponding item value from the following object using Javascript/JQuery?

var choose_one = {
  "key 1" : "item 1",
  "key 2" : "item 2",
  "key 3" : "item 3"
};

Many thanks.

sdgluck
  • 24,894
  • 8
  • 75
  • 90
user884899
  • 81
  • 1
  • 6

5 Answers5

1

You could use Math.random in combination with Object.keys.

var choose_one = {
  "key 1" : "item 1",
  "key 2" : "item 2",
  "key 3" : "item 3"
};

var keys = Object.keys(choose_one);
var random_key = keys[Math.floor(Math.random() * keys.length)]
console.log(random_key, choose_one[random_key]);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

A quick solution using plain javascript would be generate a random number and use it using Object.keys().

var keys = Object.keys(choose_one);
var randomKey = key[Math.floor(Math.random()*keys.length)];
var value = choose_one[randomKey];
Prakhar Londhe
  • 1,431
  • 1
  • 12
  • 26
0

Use a combination of Object.keys() to get the object's keys as an array of strings, then a random number generator to produce a number in the range of the array's indices. See this answer for details on random number generation in JavaScript.

var choose_one = {
  "key 1" : "item 1",
  "key 2" : "item 2",
  "key 3" : "item 3"
};

const keys = Object.keys(choose_one)

function randomKey(keys) {
  return keys[Math.floor(Math.random() * keys.length)]
}

console.log("random value:", choose_one[randomKey(keys)])
sdgluck
  • 24,894
  • 8
  • 75
  • 90
0

You can use Math Random function it gives you a value between 0 and 1 but never 1

var choose_one = {
    "key 1" : "item 1",
    "key 2" : "item 2",
    "key 3" : "item 3"
};
let keys = []
for(var key in choose_one) keys.push(key);
let randomKey = keys[Math.floor(Math.random() * keys.length)];
let randomItem = choose_one[randomKey];
0

I prefer to do this with randojs.com to make thing simpler and more readable, like this:

var choose_one = {
  "key 1" : "item 1",
  "key 2" : "item 2",
  "key 3" : "item 3"
};

var choice = rando(choose_one);
console.log(choice.key, choice.value);
<script src="https://randojs.com/1.0.0.js"></script>

I'd show you how to do it the long way as well, but there are plenty of other answers here already doing that. If you have questions about randojs, check out the website or feel free to ask me if needed.

Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15