Gabriel Gabriel - 5 months ago 72
Javascript Question

Firebase - Object.key returns undefined

I want to order the query based on multiple values. The problem is, that I can't select the objects key

type
because I get
undefined
when I do so.

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
}
}


The second one:
TRAVEL TYPE: undefined


Any idea, where I made a mistake?

Answer

Since you will be retrieving multiple objects you need to iterate over them to get the values for each one.

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