2015-11-06 40 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'返回的值。 –

相关问题