Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick random value from firebase snapshot

I'm using firebase's foreach to get each child in a tree from this url

Objective, when the page loads grab a random item from firebase and show it

data structure

 grabbit (table name)

      active (for active items for sale)

          category (the category of the item ie womensClothes, MensShoes etc)

                 unique id of the item

On page load go into http://gamerholic.firebase.com/grabbit/active and grab any one of the categories and return it..

Script

var grabbitRef = new Firebase('https://gamerholic.firebaseIO.com/grabbit/active/');
grabbitRef.on('value', function(snapshot) {
if(snapshot.val() === null) {
alert("invalid");
} else {
  // get snap shot data:
 snapshot.forEach(function(snapshot) {

 var name = snapshot.name();
alert(name);
});

}
});

After I have a random category say "electronics", I get a new snapshot and have it return any random item that's in electronics

 var grabbitRef = new Firebase('https://gamerholic.firebaseIO.com/grabbit/active/'+name);
grabbitRef.on('value', function(snapshot) {
if(snapshot.val() === null) {
alert("invalid");
} else {
  // get snap shot data:
 snapshot.forEach(function(snapshot) {

 var id = snapshot.name();
alert(id);
});

}
});

with the id I can now get the details of the item

var grabbitRef = new Firebase('https://gamerholic.firebaseIO.com/grabbit/active/'+name+'/'+id);
like image 809
user2320607 Avatar asked Sep 24 '13 19:09

user2320607


1 Answers

It's not possible to grab a random item from the list in Firebase, unfortunately. You can do limit(1) to grab the first item, or endAt().limit(1) to grab the last item.

If you're using forEach, you can also grab all the items like you are and then picking one at random, using Math.random. For example:

var i = 0;
var rand = Math.floor(Math.random() * snapshot.numChildren());
snapshot.forEach(function(snapshot) {
  if (i == rand) {
    // picked random item, snapshot.val().
  }
  i++;
});
like image 151
Anant Avatar answered Nov 20 '22 18:11

Anant