Home > other >  Use Variables for ChildSnapshot - Keys in Firebase (JavaScript)
Use Variables for ChildSnapshot - Keys in Firebase (JavaScript)

Time:09-17

I would like to use a variable for the ChildSnapshot but it does not work. This is how it works.

firebase.database(CustomerDatabase).ref('Customer').once('value', function (snapshot) {
    snapshot.forEach(function (ChildSnapshot) {
        console.log(ChildSnapshot.val().Firstname);
    }

This is how I would like it to work. But that throws an error.

let child_var = "Firstname";
firebase.database(CustomerDatabase).ref('Customer').once('value', function (snapshot) {
    snapshot.forEach(function (ChildSnapshot) {
        console.log(ChildSnapshot.val().child_var);
    }

Help appreciated.

CodePudding user response:

You'll want to use [] notation for that:

console.log(ChildSnapshot.val()[child_var]);

CodePudding user response:

This is a common JavaScript problem. What you are actually doing in the second code block is attempting to access the property named "child_var" instead of the one named "Firstname". Use bracketed property access to use a variable to access properties:

ChildSnapshot.val()[child_var]

Further reading: JavaScript property access: dot notation vs. brackets?

  • Related