Ben Gubler Ben Gubler - 3 years ago 294
Javascript Question

Get first firebase child without key

I am trying to get the first child of a firebase object. My ref looks like this:

var sitesToVisitRef = firebase.database().ref('sitesToVisit')


I know the ref works because I can write to it. My data structure can look like this:

sitesToVisit:
arstechnica-com:
url: "https://arstechnica.com"


However, I don't know the key (arstechnica-com), but I need to get the url.

I am trying to with this code:

var nextUrl;
sitesToVisitRef.limitToFirst(1).once('value', function(snapshot) {
console.log("snapshot key" + snapshot.key);
console.log("snapshot.val.url = " + snapshot.val().url);
console.log("snapshot.val" + snapshot.val());
nextUrl = snapshot.val().url;
}
});


But snapshot.key logs as "sitesToVisit", not "arstechnica-com".

Any help would be greatly appreciated. Thank you so much!

Answer Source

Try this:

var nextUrl;
sitesToVisitRef.limitToFirst(1).once('value', function(snapshot) {
    for(var key in snapshot.val()){
        console.log("snapshot key" + key);
        console.log("snapshot.val.url = " + snapshot.val()[key].url);
        console.log("snapshot.val" + snapshot.val()[key]);
        nextUrl = snapshot.val()[key].url;
    }
  });

What you have in snapshot is an array with all the childs in sitesToVisit, since you used limitToFirst(1) it's only the forst one, but it still is an array so you need to iterate over that array to get the key of each child.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download