簡體   English   中英

Firestore 從動態鍵字段或變量中獲取值

[英]Firestore Get value from dynamic key field or from variable

我從 Firestore 檢索值時遇到問題,我的字段鍵是動態的。

我有這個代碼用於向我的數據庫添加新字段:

db.collection('programacio')
    .doc(idSetmana)
    .set(
        {
            [id]: valor
        },
        { merge: true }
    )
    .then(function () {
        console.log('Document successfully written!');
    })
    .catch(function (error) {
        console.error('Error writing document: ', error);
    });

但是當我無法從變量中獲取此 id 值時。 例如,如果我有以下代碼:

db.collection('programacio')
    .doc(id)
    .get()
    .then(function (doc) {
        if (doc.exists) {
            var cell;
            var numFiles = $('#tbody_programacio tr').length;
            var numColumnes = 5;
            for (let i = 0; i < numFiles; i++) {
                for (let j = 1; j < numColumnes; j++) {
                    cell = 'fila' + i + 'columna' + j;
                    var hola = doc.data().cell; <<<<<<< Cell doesn't work because isn't a field's name
                }
            }
        } else {
            // doc.data() will be undefined in this case
            console.log('No such document!');
        }
    })
    .catch(function (error) {
        console.log('Error getting document:', error);
    });

我可以從變量的鍵名中獲取值嗎?

如果不可能,我的目標是將表中的每個單元格保存到我的數據庫中,當我單擊該單元格時返回數據庫值,但我不知道是否可以通過其他方式...謝謝大家!

您正在尋找[] (括號)符號:

var hola = doc.data()[cell];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM