如何使用Firebase和JavaScript解析此数据快照?

时间:2017-05-25 09:03:43

标签: javascript firebase firebase-realtime-database

我有这个数据结构

{
  "job-requests" : {
    "pending" : {
      "-KkyZGfqmiIVryyLAZpD" : {
        "job_details" : "asd",
        "job_type" : "Repair Required",
        "location" : "123",
        "location_lat" : 14.164633210106128,
        "location_lng" : 121.24110514763743,
        "timestamp" : 1495698316411
      }
    }
  },
  "office-info" : {
    "123" : {
      "office_acronym" : "123",
      "office_contact_number" : "123-1234",
      "office_current_head" : "None",
      "office_name" : "123",
      "office_parent_unit" : "123"
    }
  },
  "office-location-list" : {
    "123" : {
      "location_lat" : 14.164633210106128,
      "location_lng" : 121.24110514763743
    }
  },
  "users" : {
    "MBR5o37xafUyuLw14Xqa1ku0Zui1" : {
      "designation" : "staff",
      "email" : "123@asd.com",
      "given_name" : "23",
      "last_name" : "123",
      "password" : "1234567",
      "timestamp" : 1495617328793
    },
    "Nwacy3ADczgLC85OvSAgUNEGMkx2" : {
      "designation" : "staff",
      "email" : "adsasd@asdas.com",
      "given_name" : "122123",
      "last_name" : "12",
      "password" : "asdasdsadasd",
      "timestamp" : 1495681430048
    }
  }
}

我将需要键[pending, active, finished]以及新添加的孩子的数据。这就是我访问Firebase的方式

   firebase.database ().ref ('job-requests').on ('child_added', (snapshot) => {
    console.log (snapshot.key); // prints out [pending, active, finished]
    console.log (snapshot.val()); // prints out an object
});

它在控制台上打印:

Screenshot of console

我尝试使用JSON.parse ()snapshot.child (path)snapshot.fieldsnapshot[field],但错误被抛弃了。我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

您的代码获得所有作业请求。由于它们的状态属于层次结构,因此您的代码需要处理:

firebase.database ().ref ('job-requests').on ('child_added', (snapshot) => {
  snapshot.forEach((stateSnapshot) => {
    console.log(stateSnapshot.key); // 'pending', etc
    stateSnapshot.forEach((jobSnapshot) => {
      console.log(jobSnapshot.key);
      console.log(jobSnapshot.val());
    });
  });
});