Daniel ORTIZ
Daniel ORTIZ

Reputation: 2520

Retrieve Keys and elements of Array Firebase Database

I'm working with Firebase realtime database and I want to retrieve an array data:

Data:

enter image description here

And my function:

   function traerUsuarios(firebase)
{
    var ref = firebase.database().ref().child('/Usuario');
    console.log(ref)
    ref.once('value', function (snap) {
        snap.forEach(function (item) {
            var itemVal = item.val();
            console.log(itemVal);
        });
        });
}

But the result:

Show me object but no de for of the items

enter image description here

What im doing wrong?

Upvotes: 0

Views: 2487

Answers (2)

Daniel ORTIZ
Daniel ORTIZ

Reputation: 2520

Thanks to @MarksCode , I fixed the function with data refs:

function traerUsuarios(firebase) {  var key;
var starCountRef;
var usuarios=new Array();
// var ref = firebase.database().ref().child('/Usuario');
var query = firebase.database().ref("/Usuario").orderByKey();

query.once("value")
        .then(function (snapshot) {
            snapshot.forEach(function (childSnapshot) {
                // key will be "ada" the first time and "alan" the second time
                key = childSnapshot.key;
                starCountRef = firebase.database().ref("/Usuario/"+key);
                starCountRef.on('value', function (snapshot) {
                    console.log(snapshot.val());
                    usuarios.push([key,snapshot.val()]);
                });

            });
        }); }

And the result show me the values:

enter image description here

Upvotes: 0

MarksCode
MarksCode

Reputation: 8584

Each item in your for loop are the children of Usario. Each of these children (from your picture 056BN.., CQL.., and E4ll) have an object as their value (hence why they have a + next to them in the database).

So when you say item.val() you're getting the value of each one of those children, which is their corresponding object (The data you see when you click the + in the database.

Upvotes: 1

Related Questions