Javascript get array key by index number

0
88
Asked By Elli Mongillo On

I have an array of items where they are key value pairs. I want to select one at random, but I do not know how to get the key for a random item in the array. I can use Math.random() to generate a random index but how do i get the key?

Here is the array that I am working with. All I want is to get one of these values randomly but I want to know the name as well as the ID.

{ "bob": 1, "john": 2, "sam": 3, "tom": 4 }

 

1 Answer

Answered By Dan On

While arrays and objects are sort of the same thing in Javascript, the example you are using here is not behaving like a normal array, this is an object and what you are trying to do is access a random property of that object. While this is still possible to do, using a numeric index to access a string key property of an object isn't going to work for you.

The following code snippet will allow you to access the property name and value for a random property of any javascript object.

var keys = Object.keys(objectarray);
var key = keys[ keys.length * Math.random() << 0];
var value = objectarray[key];

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.