0

I'm stuck during fetching Firebase data. How to read Firebase object?

the key like : -KYl7Q_gcndAPqFC2eCn makes me stuck to fetch it. How do I know that object name?

** This fetch is for public blog.

// Initialize Firebase
var config = {
  apiKey: "foobarbaz",
  authDomain: "whatever.com",
  databaseURL: "foo.com",
  storageBucket: "bar.com",
  messagingSenderId: "1234567890000"
};
firebase.initializeApp(config);

firebase.database().ref("pelanggan").on('value', function(snapshot) {
  var pelanggan = snapshot.val();
  console.log(pelanggan);
  var div_senarai_pelanggan = document.getElementById('div_senarai_pelanggan');

  console.log(key);
  var html = "";
  html = '<ol>';
  pelanggan.foreach(a, function(key, value) {
    console.log(key);
  })
  html += '</ol>';
  div_senarai_pelanggan.innerHTML = html;

});

Here's my fiddle.

Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
Nere
  • 4,097
  • 5
  • 31
  • 71
  • 2
    i would recommend changing your API key ASAP since you've now publicized it to the internet – imjared Dec 12 '16 at 04:22
  • 1
    @imjared: the API key in that configuration snippet just identifies a project, much like a URL does. All of this is publicly shareable, in fact: you will need to share it with your users to ensure they can access your app. See [Is it safe to expose Firebase apiKey to the public?](http://stackoverflow.com/questions/37482366/is-it-safe-to-expose-firebase-apikey-to-the-public). – Frank van Puffelen Dec 12 '16 at 15:08

1 Answers1

1

Firebase stores your contents in object format. You should be able to see this in your console.log() call. forEach() is a method specific to arrays so you wouldn't be able to call it on an object. You'll need to iterate over the collection of objects using

Object.keys( pelanggan ).forEach( function( key ) {
    console.log( pelanggan[ key ] );
});

If you want to use a variation of .forEach(), I'd recommend using Lodash's implementation then you can do what you're trying to do with

_.forEach( pelanggan, function( item ) {
    console.log( item );
});
imjared
  • 19,492
  • 4
  • 49
  • 72