如何使用javascript从firebase实时数据库中检索对象数组?

时间:2022-07-01 12:33:01

This is my database.

这是我的数据库。

如何使用javascript从firebase实时数据库中检索对象数组?

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

我正在尝试遍历每个对象并将“Name”值打印到控制台。

This is my JS code

这是我的JS代码

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]

snap = {rootKey:[对象数组]

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

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

scores[1] = {Name : Josh}

得分[1] = {姓名:Josh}

scores[1].Name = Josh

得分[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]);
});

如何使用javascript从firebase实时数据库中检索对象数组?

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

如此处所示,我无法访问数组中的对象。

1 个解决方案

#1


0  

try

尝试

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

#1


0  

try

尝试

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