简体   繁体   English

Firestore 从动态键字段或变量中获取值

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

I have a problem retrieving a value from Firestore where my field key it's dynamic.我从 Firestore 检索值时遇到问题,我的字段键是动态的。

I have this code for add new fields to my DB:我有这个代码用于向我的数据库添加新字段:

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);
    });

But when I can't get this id value from a variable.但是当我无法从变量中获取此 id 值时。 For example, if I have this code:例如,如果我有以下代码:

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);
    });

Can I get value from a key name from a variable?我可以从变量的键名中获取值吗?

If isn't possible, my objective is save every cell from a table to my DB and when I click on that cell return the DB value, but I don't know if it's possible with another way... Thanks for all!如果不可能,我的目标是将表中的每个单元格保存到我的数据库中,当我单击该单元格时返回数据库值,但我不知道是否可以通过其他方式...谢谢大家!

You're looking for [] (bracket) notation:您正在寻找[] (括号)符号:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM