0

I am new to Firebase and I am trying to learn how to retrieve nested data from Firebase and print out on a webpage. I can print out all the data in the console but not on the webpage and I will get back [object Object] on the webpage. Can someone please kindly explain to me why is my webpage is printing out [object Object]? Is it something to do with "ref.on" or "snap =>"?

This is my function to get the data from Firebase:

function GetData()
{
  var ref = firebase.database().ref('Scores');
  var PrintData = document.getElementById('PrintOutData');

  ref.on("value", function(snapshot) 
  {
    snapshot.forEach(function(childSnapshot) 
    {
      var childData = childSnapshot.val();
      var id=childData.id;
      console.log(childData);
      ref.on('value', snap => PrintData.innerText = childData);
    });
  });
}

This is what in my console log:console.png

And this is what on my webpage: web.png

And this is my data on my Firebase:

firebase.png

What I want to get on my webpage is like this:

name:"AAA", score:100, time:"30s"
name:"AAA", score:100, time:"30s"
...

Thanks alot!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Dracarys
  • 11
  • 2

2 Answers2

0

You can use:

 let keys = Object.keys(childData)
  keys.forEach(key => {
  let value = childData[key.toString()];
  console.log(value) // Use Value
  })
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
0

Yikes, that looks pretty bad. Not sure why you're nesting an on("value" listener, and I also don't know where .id comes from. You're probably looking for something along these lines:

ref.on("value", function(snapshot) {
  PrintData.innerText = ""; // We got a new value, so clear the existing HTML
  snapshot.forEach(function(childSnapshot)  {
    var childData = childSnapshot.val();
    PrintData.innerText += "name: " + childData.name + " score: " + childData.score + " time: " + childData.time + "    ";
  });
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807