我应该如何构建我的数据以使其与firebase一起使用?

时间:2015-11-06 18:31:52

标签: 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吗?或其他什么?

目前我只能使用firebase .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}
            ];

其中每个word-object是数组中的索引。

以下是我构建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);
        }
    }
}

1 个答案:

答案 0 :(得分: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将其添加到Firebase。

var wordMap = {};
wordObjects.forEach(function(wordObject) {
  wordMap[wordObject.word] = wordObject;
});
ref.update(wordMap);
相关问题