AJ_91
AJ_91

Reputation: 581

How do I retrieve a random object from an array of objects ? Javascript

I have this bit of code that adds an image to the 'imageContainer'

$('.imageContainer').prepend('<img id="xboxLogo" src="images/xboxLogo.png"/>')

I have this array of objects :

var imagesArray = { 
    xboxLogo : {
        id : 'xboxLogo';
        src: "images/xboxLogo.png";     
    },
    playStatLogo : {
        id : 'playStatLogo';
        src: "images/playStatLogo.png"; 
    },
    wiiLogo : {
        id : 'wiiLogo';
        src: "images/wiiLogo.png";  
    }
    }

What I want to do is have a function that I call which adds the image to the 'imageContainer' but I want the image to be randomly picked from the 'imagesArray'. How do i randomly get one of the 3 (xbox,playStation,wii) images and then retrieve their attributes so I can use them to create the images ?

Upvotes: 0

Views: 1987

Answers (2)

Kostas
Kostas

Reputation: 1903

var imagesArray = [
  {
    id: 'xboxLogo',
    src: "images/xboxLogo.png"
  },
  {
    id: 'playStatLogo',
    src: "images/playStatLogo.png"
  },
  {
    id: 'wiiLogo',
    src: "images/wiiLogo.png"
  }
];

$('button').click(function() {
  var randomImage = imagesArray[Math.floor(Math.random() * imagesArray.length)];
  $('p').text(randomImage.src);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p></p>

<button>pick random</button>

Upvotes: 4

Transcendence
Transcendence

Reputation: 2696

Generate a random number that will be the index of the image you want.

var keys = Object.keys(imagesArray);
var n = keys.length;
var index = Math.floor(Math.random() * n);
var randomKey = keys[index]
var image = imagesArray[randomKey]

Upvotes: 2

Related Questions