My database looks like this
Rockport and Palmont are the cities and they have locations, the locations are many but i'm just giving an example - So I wanted to retrieve the locations name and population
I came up with this code which works and shows me "Location1" for each city
$("#button").click(function() {
var dbref = firebase.database().ref();
dbref.once("value")
.then(function(snapshot) {
snapshot.forEach(function(datasnap) {
var Location = datasnap.child("Location1/name").val();
var Population = datasnap.child("Location1/population").val();
$( "#table" ).append( "<tr><td>" + Location + "</td><td>" + Population + "</td></tr>" );
})
})
});
And the output for my html table is
SILVERTON 197
ROSEWOOD 213
It doesn't show "Location2" names and population because I didn't mention it obviously, In line 6 and 7 I can make it like this
var Location = datasnap.child("Location2/name").val();
var Population = datasnap.child("Location2/population").val();
but like I said the locations can be as many as '20' and I need to write all locations down?
any way to outcome this?
You need to loop over the child data of each city. Firebase's Snapshot
has a method forEach()
that makes this easy. You already use this to loop over the cities, but you should also use it to loop over the locations in each city:
$("#button").click(function() {
var dbref = firebase.database().ref();
dbref.once("value").then(function(snapshot) {
snapshot.forEach(function(citysnap) {
citysnap.forEach(function(locationsnap) {
var Location = locationsnap.child("name").val();
var Population = locationsnap.child("population").val();
$( "#table" ).append( "<tr><td>" + Location + "</td><td>" + Population + "</td></tr>" );
});
})
})
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.