如何使用Firebase和JavaScript解析此数据快照?
问题描述:
我有这样的数据结构如何使用Firebase和JavaScript解析此数据快照?
{
"job-requests" : {
"pending" : {
"-KkyZGfqmiIVryyLAZpD" : {
"job_details" : "asd",
"job_type" : "Repair Required",
"location" : "123",
"location_lat" : 14.106128,
"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.106128,
"location_lng" : 121.24110514763743
}
},
"users" : {
"MBR5o37xafUyuLw14Xqa1ku0Zui1" : {
"designation" : "staff",
"email" : "[email protected]",
"given_name" : "23",
"last_name" : "123",
"password" : "1234567",
"timestamp" : 1495617328793
},
"Nwacy3ADczgLC85OvSAgUNEGMkx2" : {
"designation" : "staff",
"email" : "[email protected]",
"given_name" : "122123",
"last_name" : "12",
"password" : "asdasdsadasd",
"timestamp" : 1495681430048
}
}
}
我将需要的按键[pending, active, finished]
与新加入的孩子的数据一起。这是我访问火力地堡
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
});
它打印此控制台上:
我使用JSON.parse()
,snapshot.child (path)
,snapshot.field
和snapshot[field]
尝试,但错误被抛出。我该怎么做呢?
答
您的代码获取全部工作请求。因为这些是由他们的状态的层次,您的代码将需要处理这个问题:
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());
});
});
});
+0
哦。我还没有掌握Firebase。这次真是万分感谢。 – Celestia
+0
不客气。如果我的回答很有用,请点击左侧的upvote按钮。如果它回答了您的问题,请点击复选标记以接受它。这样别人就知道你已经(充分)帮助了。 –
你应该做'snapshot.val()field' –
它返回'undefined'。 @ user7814783 – Celestia
当你执行'console.log(snapshot.val())'' –