Sudhanshu Saini
Sudhanshu Saini

Reputation: 63

Iterating Firebase children with non sequential id

var data;
var starCountRef = firebase.database().ref();
starCountRef.on("value",snap =>{
  data = snap.val();
  console.log(data);
  uid = //some uid here;
  checkifplaying(data,uid);
});
function checkifplaying(data,uid){
  var flag1 = 0;
  var pos = -1;
  console.log(data);
  data.Users.forEach(function(user){
    if(uid == user.uid){
      flag1 = 1;
      which = data.User;
    }
  });
  if(flag1 == 0){
    $("#contest3").show();
  }
  else if(flag1 == 1){
    $("#contest1").show();
    $("#contest2").show();
  }
}

My Firebase DB looks like this:

enter image description here

I am trying to iterate the Users children using forEach loop

data.Users.forEach(function(user){
})

, but it is giving an error as data.Users.forEach is not a function. data contains the whole of db which was taken through snapshot. And it contains the master object in it.

Please tell me how to iterate this.

Upvotes: 1

Views: 210

Answers (1)

Rosário P. Fernandes
Rosário P. Fernandes

Reputation: 11326

You're passing the snapshot value to your function. You should pass the snapshot object instead. Like this:

starCountRef.on("value",snap =>{
  //data = snap;
  console.log(snap.val());
  uid = //some uid here;
  checkifplaying(snap,uid);
});

And on your checkifplaying function:

function checkifplaying(data,uid){
  var flag1 = 0;
  var pos = -1;
  console.log(data);
  data.child('Users').forEach(function(user){
    if(uid == user.uid){
      flag1 = 1;
      which = data.User;
    }
  });
  if(flag1 == 0){
    $("#contest3").show();
  }
  else if(flag1 == 1){
    $("#contest1").show();
    $("#contest2").show();
  }

Upvotes: 2

Related Questions