Skip to content Skip to sidebar Skip to footer

React, Firebase: Access Values Of Json And Also Get Key Value

I am beginner working with firebase, react. I am able to get the required data from firebase based on userEmail. But I am very confused in accessing the data. firebase.database().

Solution 1:

let data = {
 "-Lhdfgkjd6fn3AA-": {
        "email": "t5@gmail.com",
        "favQuote": "this is it",
        "firstName": "t5",
        "lastName": "l5",
    },
 };
 
 console.log(Object.keys(data))//returning an array of keys, in this case ["-Lhdfgkjd6fn3AA-"]console.log(Object.keys(data)[0])
 console.log(Object.values(data))//returning an array of values of propertyconsole.log(Object.values(data)[0].email)
 
 

Do need to be careful that the above code with the hardcoded "0" as index because it assumed that your data object has only one key. If you have more key, you can't simply replace index either because property of object has no predictable sequence

Solution 2:

It's really a JavaScript question. I had to figure this out too. ...this works.

var p;
var thisLine;
p = docu.data();
for (var k in p) {
    if (p.hasOwnProperty(k)) {
        if (isObject(p[k])) {
            thisLine = p[k];
            Object.keys(thisLine).forEach(function (key, index) {
                console.log(key, index);
            });
        }
    }
}

functionisObject(obj) {
    return obj === Object(obj);
}

Solution 3:

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So your first step is that you need to loop over the snapshot in your on() callback.

The second step is that you need to call Snapshot.val() to get the JSON data from the snapshot. From there you can get the individual properties.

firebase.database().ref('/users').orderByChild('email').equalTo(userEmail).on('value', snapshot => {
    snapshot.forEach(userSnapshot => {
        let data = userSnapshot.val();
        console.log('data: ', data);
        console.log(data.email, data.firstname);
    });
})

Post a Comment for "React, Firebase: Access Values Of Json And Also Get Key Value"