【问题标题】:Retrieving data with firebase for Web使用 Firebase for Web 检索数据
【发布时间】:2016-06-21 10:15:36
【问题描述】:

我正在尝试从 firebase 数据库中检索数据:

firebase.database().ref("/appointments").orderByChild("doctor").equalTo(doctorId).on("value", function(snapshot) {
  var appointmentsData = snapshot.val();
  for(var appointment in appointmentsData) {
    if (!appointmentsData.hasOwnProperty(appointment)) continue;
    var obj = appointmentsData.appointment;
  }
});

如果我使用console.log 约会或console.log 约会数据,我会得到正确的值,但如果我使用console.log 约会数据.约会,我会得到未定义的值。

知道如何从 firebase 返回的对象中检索属性和值吗?

【问题讨论】:

  • 当您对 Firebase 数据库执行查询时,可能会有多个结果。所以快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。 @theblindprophet 的回答显示了如何遍历列表。

标签: javascript firebase firebase-realtime-database


【解决方案1】:

您想使用Firebase 内置的forEach 函数。它允许您遍历快照并轻松获取该对象内每个属性的键和值。它可以是另一个对象或平面值。

firebase.database().ref("/appointments").orderByChild("doctor").equalTo(doctorId).on("value", function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
        // key
        var key = childSnapshot.key;
        // value, could be object
        var childData = childSnapshot.val();
        // Do what you want with these key/values here
        ...
    });
});

参考:

forEach, Firebase 3.0

【讨论】:

  • 非常感谢!这应该已经出现在 firebase 入门指南中
猜你喜欢
  • 2016-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
相关资源
最近更新 更多