-1

I have a reference to "a" named as 'ref'. And I want to read all the key(name,age and car) of the child of the reference. If my JSON looks like ths:

{"a":{ "name":"John", "age":30, "car":null } }

2 Answers2

1

The following should do the trick:

  firebase
    .database()
    .ref('a')
    .once('value')
    .then(function (snapshot) {
      var valObj = snapshot.val();
      for (var key in valObj) {
        var value = valObj[key];
        console.log(key + ': ' + value);
      }
    });

As explained in the doc:

Any time you read data from the Database, you receive the data as a DataSnapshot. A DataSnapshot is passed to the event callbacks you attach with on() or once(). You can extract the contents of the snapshot as a JavaScript object by calling the val() method.

We use one of the techniques described here to loop over all the properties of the object.


If you know the names of the properties you want to get, you can do, for example:

  firebase
    .database()
    .ref('a')
    .once('value')
    .then(function (snapshot) {
      var valObj = snapshot.val();
      console.log(valObj.name);
      console.log(valObj.car);
    });
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
0
  firebase
    .database()
    .ref('a').on("child_added", snap => {
 });
Anteos1
  • 99
  • 1
  • 10