1

I have a denormalized data as follows:

- geohash
  - w22
    - qt4
      - vhy
        - e1c
          - IzjfhqsUhJU_XQSBGTv
            - authorid: 
            - authorname: 
            - content: 

           -Izjv10JcaS7fae6dmqb
            - authorid: 
            - authorname: 
            - content: 
      - vhz
        - erc
          -Izjv10JcaS7fae6dmqb
            - authorid: 
            - authorname: 
            - content: 
  - z99
    - qt4
      - abd
        - 4g5
          -Izjv10JcaS7fae6dmqb
            - authorid: 
            - authorname: 
            - content: 

I want to list all values for authorid, authorname, content under geohash/w22/qt4. But I don't know ahead of time what the children names are or exactly how many are at that level in the hierarchy.

What should the code look like to enumerate the subchildren at this shallow level?

    var fooRef = new Firebase('firebaseRef/geohash/w22/qt4');
    fooRef.on('child_added', function(snapshot) {  
      //Need help here.
    });
Vikrum
  • 1,941
  • 14
  • 13
vzhen
  • 11,137
  • 13
  • 56
  • 87

1 Answers1

1

When you need to get a hold of children at a shallow level and you don't know the key names before hand you can use DataSnapshot.forEach() for enumeration. Alternatively, you can get the JS object at the parent level via DataSnapshot.val() and enumerate against the raw object using normal JS object/key enumeration; see also: How to list the properties of a javascript object.

So, to fill out your example, it would look like this:

var fooRef = new Firebase('firebaseRef/geohash/w22/qt4');
fooRef.on('child_added', function f(snapshot) { 
  snapshot.forEach(function(level1) {
     level1.forEach(function(level2) {
        var entry = level2.val(); // contains the JS object with authorid, authorname, ...
        var pathToEntry = snapshot.name() + "/" + level1.name() + "/" + level2.name(); // contains the path with the unknown children names
     });
  });
});

I have created a JSFiddle with an example Firebase with data populated as described, as well as code that pulls the subchildren entries out. Please take a look here: http://jsfiddle.net/guy5n/1/

Community
  • 1
  • 1
Vikrum
  • 1,941
  • 14
  • 13