2017-05-25 46 views
0

我有這樣的數據結構如何使用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 
}); 

它打印此控制檯上:

Screenshot of console

我使用JSON.parse()snapshot.child (path)snapshot.fieldsnapshot[field]嘗試,但錯誤被拋出。我該怎麼做呢?

+1

你應該做'snapshot.val()field' –

+0

它返回'undefined'。 @ user7814783 – Celestia

+0

當你執行'console.log(snapshot.val())'' –

回答

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()); 
    }); 
    }); 
}); 
+0

哦。我還沒有掌握Firebase。這次真是萬分感謝。 – Celestia

+0

不客氣。如果我的回答很有用,請點擊左側的upvote按鈕。如果它回答了您的問題,請點擊複選標記以接受它。這樣別人就知道你已經(充分)幫助了。 –