Javascript get array key by index number

77 views
0

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.

 

Changed status to publish
0

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.

Changed status to publish