I am trying to get the first child of a firebase object. My ref looks like this:
var sitesToVisitRef = firebase.database().ref('sitesToVisit')
sitesToVisit:
arstechnica-com:
url: "https://arstechnica.com"
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;
}
});
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.