无法包含父密钥,无法获得Firebase输出

时间:2017-03-19 17:30:12

标签: javascript json firebase firebase-realtime-database

我的uni小组正在尝试创建一个简单的博客应用,但我们遇到了在不使用JSON.stringify的情况下将firebase数据输出到网站的问题。目前我们的代码是

dbRefObject.on('value',snap =>
    {
        preObject.innerText = JSON.stringify(snap.val(), null, 3);
    });
    dbRefList.on("value", function(snapshot)
    {
        var newPost = snapshot.val();

    dbRefList.on("child_added", function(newPost,pre)
        {
        newchild=newPost.val();
        ulList.innerHTML = "<pre>" + "Title: "+ newchild.Title +
        "\n"+"Message: "+ newchild.Message +
        "\n"+ "Posted: "+ newchild.Posted +"</pre>";
        });

preObject.innerText的输出是。

   {
   "Posts": {
      "-KfXaHa8MKi4Qzsro3Hk": {
         "Message": "out with friends",
         "Posted": "Date: 18/3/2017 @ 18:6:13",
         "Title": "time out"
      },
      "-KfZ3r08lhIuEM9mb5GV": {
         "Message": "this is a test",
         "Posted": "Date: 19/3/2017 @ 0:59:24",
         "Title": "testing"
      },
      "-KfZY8zgUDJU_SooEvEO": {
         "Message": "03:11 am and this is kind of working.",
         "Posted": "Date: 19/3/2017 @ 3:11:46",
         "Title": "the time is now"
      },
      "-KfZiAijlWNU6-1RGdh9": {
         "Message": "The time is now 03:59 and things are coming good finally.",
         "Posted": "Date: 19/3/2017 @ 3:59:57",
         "Title": "Latest Progress"
      },
      "-KfZrtZU4pkgejOQ8N78": {
         "Message": "Ok time is 04:42 going to my bed.",
         "Posted": "Date: 19/3/2017 @ 4:42:24",
         "Title": "Final Post"
      },
      "-Kf_H-Lg2KOIjtOdALEf": {
         "Message": "5676576756575",
         "Posted": "Date: 19/3/2017 @ 6:36:27",
         "Title": "5675675"
      }
   }
}

我们希望代码输出每个Key的子代码而不显示密钥。我努力在firebase文档上找到任何东西来帮助解决这个问题,所以我想问一下,希望我已经提供了足够的信息,谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用每个帖子迭代帖子:

var obj = snap.val();
for (var key in obj.Posts) {
  var post = obj[key];
  console.log(post.Title + ", " + post.Message + ", " + post.Posted);
}

(如果需要,变量key包含字母数字键)