简体   繁体   中英

How to retrieve an array of objects from a firebase realtime database using javascript?

This is my database.

在此处输入图片说明

I'm trying to iterate through each object and print "Name" value to the console.

This is my JS code

var scores = [];

var database = firebase.database();

database.ref().once("value", function(snap){
   scores = snap.val();
});

console.log(scores[1].Name);

From my understanding this is what happens.

snap = {rootKey : [array of objects]

scores = snap.val() = [{Name : Babara}, {Name : Josh}, ......]

scores [1] = {Name : Josh}

scores [1] .Name = Josh

EDIT

When I try to print whole array I get this.

database.ref().once("value", function (snap) {
    scores = snap.val();
    console.log(scores);
    console.log(scores[1]);
});

在此处输入图片说明

As seen here, I can't access objects inside the array.

try

database.ref().once("value", function(snap){
   snap.forEach(function(childSnap) {
      scores['Name'].push(childSnap.val().Name);
      scores['Score'].push(childSnap.val().Score);
   });
});

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