1

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.

Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734
ZBop
  • 27
  • 3

2 Answers2

0

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

console.log(ChildSnapshot.val()[child_var]);
Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734
0

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?

Ian
  • 5,146
  • 5
  • 40
  • 66