Pick random value from firebase snapshot

前端 未结 2 1272
自闭症患者
自闭症患者 2021-01-05 23:09

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 str

相关标签:
2条回答
  • 2021-01-05 23:58

    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++;
    });
    
    0 讨论(0)
  • 2021-01-06 00:05

    One way to implement this is to store an additional child attribute with each element of your list that will take on a random value. Let's call the name of this attribute "randomVal".

    To pick your random entry you would use orderByChild("randomVal") and then limit the query to returning exactly one entry. Immediately upon fetching this entry, you would write a new random value into the "randomVal" element.

    Beyond the additional bookkeeping work, the biggest downside of this approach is that it requires a write to the database every time you want to select a random element. I'm new to firebase, so I don't know how significant this drawback is.

    Also, make sure to index this part of the database on "randomVal" to improve the query performance.

    0 讨论(0)
提交回复
热议问题