kumar111
kumar111

Reputation: 33

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().ref('/users').orderByChild('email').equalTo(userEmail).on('value', data => {
        console.log('data: ', data);
    })

I get the following output:

data:  Object {
"-Lhdfgkjd6fn3AA-": Object {
        "email": "[email protected]",
        "favQuote": "this is it",
        "firstName": "t5",
        "lastName": "l5",
    },
 }

Please help me how to access all values ("-Lhdfgkjd6fn3AA-" , firstname, lastname, email and favQuote) into variables like: data.firstName, data.lastName, data.key, etc . Thank you.

Upvotes: 0

Views: 3604

Answers (3)

Frank van Puffelen
Frank van Puffelen

Reputation: 600006

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);
    });
})

Upvotes: 0

Ronnie Smith
Ronnie Smith

Reputation: 18585

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);
            });
        }
    }
}

function isObject(obj) {
    return obj === Object(obj);
}

Upvotes: 1

Isaac
Isaac

Reputation: 12894

let data = {
 "-Lhdfgkjd6fn3AA-": {
        "email": "[email protected]",
        "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 property
 console.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

Upvotes: 2

Related Questions