2015-11-06 42 views
0

我想在形式我應該如何構建我的數據以便與Firebase一起使用?

wordBank = {    
      {word:"aprobi", translation:"to approve", count:2}, 
      {word:"bati", translation:"to hit, to beat, to strike", count:1}, 
      {word:"da", translation:"of", count:1} 
     } 

的目標是能夠提取並顯示在每個JSON對象的所有鍵的所有值更新一些數據。如何在Firebase上創建此格式?我使用.update?或者是其他東西?

目前我只能得到火力.update()與數組的工作,但它使我的數據是這樣

wordBank = [ 
      {word:"aprobi", translation:"to approve", count:2}, 
      {word:"bati", translation:"to hit, to beat, to strike", count:1}, 
      {word:"da", translation:"of", count:1} 
      ]; 

其中每個字對象是在數組中的索引。

下面是如何構建我的wordObjects:

function getWords() { 
    if (document.getElementsByClassName("vortarobobelo").length != 0){ 
     var words; 
     words = document.getElementsByClassName("vortarobobelo")[0].children[0].children; 

     for (var i =0; i < words.length; i++) { 
      var localBank = {} //creating the local variable to store the word 
      var newWord = words[i].children[0].innerText; // getting the word from the DOM 
      var newTranslation = words[i].children[1].innerText; // getting the translation from the DOM 

      localBank.word = newWord; 
      localBank.translation = newTranslation; 
      localBank.count = 0 //assuming this is the first time the user has clicked on the word 

      console.log(localBank); 
      wordBank[localBank.word] = localBank; 
      fireBank.update(localBank); 
     } 
    } 
} 

回答

0

如果你想存儲對象中的項目,你需要挑鍵將它們存儲反對。

您不能在JavaScript中的對象內存儲無密鑰值。這將導致一個語法錯誤:

wordBank = {    
    {word:"aprobi", translation:"to approve", count:2}, 
    {word:"bati", translation:"to hit, to beat, to strike", count:1}, 
    {word:"da", translation:"of", count:1} 
} 

另一種選擇是將它們存儲在一個陣列中,在這種情況下,各鍵將被自動指定爲數組索引。就像你的第二個例子。

也許你想存儲單詞對象,使用單詞本身作爲一個關鍵?

wordBank = {    
    aprobi: {word:"aprobi", translation:"to approve", count:2}, 
    bati: {word:"bati", translation:"to hit, to beat, to strike", count:1}, 
    da: {word:"da", translation:"of", count:1} 
} 

這對Firebase很容易。假設您將所有單詞對象都作爲列表。

var ref = new Firebase("your-firebase-url"); 
wordObjects.forEach(function(wordObject) { 
    ref.child(wordObject.word).set(wordObject); 
}); 

或者你可以用JavaScript創建對象,然後將其添加使用.update到火力地堡。

var wordMap = {}; 
wordObjects.forEach(function(wordObject) { 
    wordMap[wordObject.word] = wordObject; 
}); 
ref.update(wordMap); 
+0

用單詞存儲每個對象作爲鍵聽起來像個好主意。但是,當我試圖這樣做時,而不是更新數據庫,它只是覆蓋它。 –

+0

使用[Object.assign](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)將舊對象與新對象合併,然後調用'set'返回的值。 –

相關問題