【问题标题】:How should I structure my data so it works with firebase?我应该如何构建我的数据以便它与 firebase 一起使用?
【发布时间】:2015-11-06 18:31:51
【问题描述】:

我想以

的形式更新一些数据
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}
            ];

其中每个词对象是数组中的一个索引。

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

【问题讨论】:

    标签: firebase


    【解决方案1】:

    如果您想将项目存储在一个对象中,您需要选择键来存储它们。

    您不能在 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);
    

    【讨论】:

    • 用单词作为键存储每个对象听起来是个好主意。但是,当我尝试这样做时,它并没有更新数据库,而是覆盖它。
    • 使用Object.assign将旧对象与新对象合并,然后用返回值调用set
    猜你喜欢
    • 2015-06-02
    • 2011-01-15
    • 2021-02-21
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    相关资源
    最近更新 更多