2016-01-06 24 views
0

這裏是我的JSON和Code,它只給出數組,但不給它賦值。正如我曾經推動它產生的獨特ID,我沒有得到。所有存儲在該ID中的值。如何使用JavaScript爲每個對象檢索firebase JSON中的數據

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

這有幫助嗎? https://jsfiddle.net/ab11b7h6/ – Amir

回答

2

child_added事件將觸發。

因此,如果您要查詢顯示的JSON的根目錄,child_added將觸發nitin。然後,如果我們添加puf,則child_added也會因此而觸發。

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

如果要接收項child_addedmobileperfume,你需要將這些的父節點上附上child_added

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

或者:

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

請參閱this jsbin以獲取此工作示例。

+0

謝謝@Frank van Puffelen,但是這個過程是由我完成的。我想要的是如何去尋找下一個香水的對象。再次,我創建了一個新的變量作爲你給出的建議,但它應該自動檢查是否有更多的節點是否存在,並顯示該節點 –

+0

如何獲得進入香水,移動....並獲得他們的鑰匙在他們之下並顯示它們。另外讓我知道如何創建數組的索引增量,以便我可以避免由push生成的唯一鍵,並使用純粹基於數組的數據而不是id來獲取數據。 –

+0

「避免通過push生成的唯一鍵並使用基於數組的純數據獲取數據」 - > Firebase建議不要使用數組索引:https://www.firebase.com/docs/web/guide/瞭解-data.html#段陣列式,火力 –

相關問題