【问题标题】:How to retrieve child value from child in firebase with javascript?如何使用javascript从firebase中的child检索子值?
【发布时间】:2020-05-01 16:54:23
【问题描述】:

var ref = firebase.database().ref("games/" + gameId + "/patterns");
ref.on("child_changed", function(snapshot){
  var pattern = snapshot.key;
  console.log(pattern);
});

这只是提供钥匙。 如果我想提取status = 0的玩家名字怎么办

我知道快照包含我需要提取的每个子数据,因为当我使用时

var ref = firebase.database().ref("games/" + gameId + "/patterns");
ref.on("child_changed", function(snapshot){
  var value = snapshot.val();

  console.log(value);
});

我得到这样的数据..

我无法根据需要获取孩子的数据。

【问题讨论】:

    标签: javascript firebase-realtime-database


    【解决方案1】:

    您提取的值是一个常规的 JavaScript/JSON 对象,因此您可以像访问任何其他 JavaScript 对象一样访问其成员。您的 123 级别键将被 Firebase 转换为数组,这意味着它会在该数组的开头添加一个 null 项。有关更多信息,请参阅:Firebase database returns null at beginning of each new node

    要遍历已更改的 patterns 的子节点下的所有子节点并获取 status0 的玩家,您可以执行以下操作:

    var ref = firebase.database().ref("games/" + gameId + "/patterns");
    ref.on("child_changed", function(snapshot){
      snapshot.forEach(function(child) {
        if (child.val() && child.val().status == "0") {
          console.log(child.val().player);
        });
      });
    });
    

    【讨论】:

    • 谢谢弗兰克.. 你提到的帖子清除了我所有的困惑!
    猜你喜欢
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多