简体   繁体   中英

Get key/value pairs of children

I'm trying to populate a map with key/value pairs of the data from my firebase database. Here's my database structure:

数据库结构

The highest level fields under recipes/ are the uID's, and the fields within those are the individual recipe ids. When I was retrieving just the current logged in users data, this was fine, as I was only reading one level deep, and was able to get proper key/value pairs out.

I'm trying to retrieve all of the recipes. It would be easiest if I could have a map populated with just the key/value of the individual recipe ids and their values, disregarding the uid field here, but anything that's properly stored in a map would work. But the problem I've run in to is that I can't seem to find a way to dynamically query through the uids as the only known id is the current logged in user. Here's what I've got so far:

var ref = firebase.database().ref('recipes/');
ref.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
        var childData = childSnapshot.val();
        var key = childSnapshot.key;
        allRecipesMap.set(key, childData);
    });
});

With this code, I can get a map with two key/value pairs, and the value for these is all of the children of the user. What I'd really like is to also get the key/value pairs of each of the recipes individually, not just a key of the user with the recipes being the values.

What I'd really like is to also get the key/value pairs of each of the recipes individually, not just a key of the user with the recipes being the values

To be able to do that, then you can do the following:

var ref = firebase.database().ref('recipes/');
ref.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
        childSnapshot.forEach(function(subChildSnapshot) {
        var childData = subChildSnapshot.val();
        var key = subChildSnapshot.key;
      });
    });
});

Adding another forEach will give you all the details for the recipe and its id also.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM