Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

javascript - retrieve key names from firebase react-native

I have a little problem regarding Firebase and retrieving names of parent keys. Like in this example I want to get the names of the keys, not their values:

quick sample of what I want to archieve

Pls have a look in my db how it looks now, its exactly the same like in the JS sandbox:

enter image description here

When I try to implement this in my react-native project, basicly with plain JS in this part, it looks like this:

const sendletter = () => {
        console.log("letter send");
        firebase.database().
        refFromURL("https://SOMEDATABASE.firebaseio.com/numers").
        once("value").then(snapshot => {
            for(key in snapshot){
                console.log(key)
            }
        })
    };

The problem I just face now it the outcome of the console in my IDE:

null letter send node_ ref_ index_ val exportVal toJSON exists child hasChild getPriority forEach hasChildren key numChildren getRef ref

I tried to provide you as many pictures so the problem gets really clear and also my goal I want to archieve, to get the key names itself, NOT the values the keys are linked to. Any help would be appriciated!

question from:https://stackoverflow.com/questions/65868111/retrieve-key-names-from-firebase-react-native

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You want to use snapshot.val() instead of just the DataSnapshot object

for(key in snapshot.val()){
                console.log(key);
            }

When you are looping through just the snapshot variable, you are looking at all the keys in that DataSnapshot that is returned from firebase and not your actual data. If you check out Firebase docs, you'll see what the DataSnapshot object represents and how to actually get your data from the database FROM their DataSnapshot object that is returned: https://firebase.google.com/docs/reference/node/firebase.database.DataSnapshot

If you look close enough you can see that all the methods and values that this DataSnapshot object contains is actually what was being printed in your console all along


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...