Firebase - Object.key returns undefined

I want to order a request based on several values. The problem is that I cannot select the type object key, because I get undefined when I do this.

 var filterDataAccordingToDate = function(ref, startTime, endTime, travelType) { ref.orderByChild('date') .startAt(startTime).endAt(endTime) .once('value', function(snapshot) { var travel = snapshot.val(); console.log("TRAVEL OBJ: " + util.inspect(travel, false, null)); console.log("TRAVEL TYPE: " + travel.type); if (travel.type == travelType) { // DO STUFF } }); } 

The first console.log() returns the correct object:

 TRAVEL OBJ: { "-KKiZKAVH0-QulKnThhF" : { "date" : 1466439009, "dest" : 1, "fbKey" : "-KKiZKAVH0-QulKnThhF", "type" : 1 } } 

Second: TRAVEL TYPE: undefined

Any idea where I made a mistake?

+4
source share
2 answers

Since you will be extracting multiple objects, you need to iterate over them to get values ​​for each of them.

 for (var key in travel) { console.log("TRAVEL OBJ: " + util.inspect(travel[key], false, null)); console.log("TRAVEL TYPE: " + travel[key].type); } 
+2
source

Use the .forEach() method on a DataSnapshot

 snapshot.forEach(function(snap) { var key = snap.key; if (key === travelType) { // Do stuff } }); 
+3
source

All Articles