javascript - 如何使用 JavaScript 从 firebase JSON 检索每个对象的数据

标签 javascript json firebase firebase-realtime-database

这是我的 JSON 和代码,它只提供数组,但不提供值。因为我已经使用了 Push 它生成唯一 ID,但我没有得到。存储在该 id 中的所有值。

{
  "nitin" : [ {
    "mobile" : {
      "-K7GalDi5aAahDENCRi" : {
        "name" : "file:///D:/Software%20Drive/addItem.html?category=mobile",
        "price" : 345,
        "quantity" : 34
      }
    },
    "perfume" : {
      "-K7K7HSu4rQNwbH3ud0H" : {
        "name" : file:///D:/Software%20Drive/addItem.html?category=perfume",
        "price" : 1000,
        "quantity" : 20
      }
    }
  }]
}

这是我的代码

  fbref.on("value", function(snapshot) {
      var newPost = snapshot.val();
      console.log(newPost);
      fbref.on("child_added", function(newPost,pre){
          newchild=newPost.val();
          console.log(newchild); 
          var n=newPost.key();
          console.log("this is key"+n);
          console.log("Name"+newchild.name);
          console.log("Price"+newchild.price);
          console.log("Quantity"+newchild.quantity);
      });  
  });

最佳答案

当子节点直接添加到您正在查询的位置下时,child_added 事件将会触发。

因此,如果您正在查询所显示的 JSON 的根,则会针对 nitin 触发 child_added。然后,如果我们添加 pufchild_added 也会为此触发。

{
  "nitin" : [ {
    ...
  }],
  "puf": [ {
    ...
  }],
}

如果您想收到 mobileperfume 内的商品的 child_added,则需要附加 child_added code> 在这些的父节点上:

fbref.child('nitin').child(0).child('mobile').on('child_added'...

或者:

fbref.child('nitin/0/mobile').on('child_added'...

参见this jsbin获取此工作示例。

关于javascript - 如何使用 JavaScript 从 firebase JSON 检索每个对象的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34634860/

相关文章:

javascript - 来自 Json 的 Google 图表 "undefined is not a function"

swift - 根据数据动态加载 UIController 的各个部分

javascript - 使用 Angularjs 在同一页面上显示多个图表

Javascript camel case split for json 结果

javascript - 在子窗口提交后如何在父窗口上重新加载文本

c# - 反序列化没有唯一属性名称的 JSON

javascript - 循环访问对象时,如何以编程方式创建同名变量?

ios - NSObject does not have a member named Key 错误

ios - ionic 3 : Unable to receive push notification on foreground in IOS

firebase - Firebase CLI 只能运行预部署步骤吗?