ForEach is not a function when trying to loop through a Firebase result set:

I'm trying to port some of my Firebase database calls to an IOT board that doesn't have jQuery, just old old JavaScript.

In my code, I originally had jQuery $.each(tripData, function(index, element)

 ... a loop to iterate over the results.

I switched this to:

var tripsRef;
tripsRef = firebase.database().ref('trips/');
tripsRef.orderByChild('timestamp').limitToLast(100).on('value', function (response) {
var tripData = response.val();
tripData.forEach(function (index, element) {
    if (element.status >= 0) {
        var trip = new Object();
        trip.id = index;
        trip.launch = element.launch;
        trip.status = element.status;
    }
});

      

... but I am getting the following error:

forEach is not a function

I'm not sure how to resolve this.

+3


source to share


4 answers


for(let index in tripData){
  element = trimpData[index];
}

      

not really foreach, but it works like that.



but you can also use map functions

+5


source


You really need to figure out if your answer is an array or an object. $.each()

iterates over arrays and objects, so it works.

you should use the statement for...in

if you really want to iterate over this object tripData

.



for(let prop in tripData)
{ 
   if (tripData.hasOwnProperty(index))
   { 
     item = tripData[prop];
      // do stuff
    }
}

      

learns about for...in

here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

+3


source


While @TypedSource's answer will iterate over the resulting children, the order in which it is executed is undefined and most likely won't be by timestamp.

The resulting snapshot contains three pieces of information for each child: its key, its meaning, and its position relative to other children. When you call .val()

on a snapshot, you lose the relative ordering.

To keep order, use the built-in forEach()

snapshot method :

var tripsRef;
tripsRef = firebase.database().ref('trips/');
tripsRef.orderByChild('timestamp').limitToLast(100).on('value', function (response) {
  var index = 0;
  response.forEach(function (child) {
    var element = child.val();
    if (element.status >= 0) {
      var trip = new Object();
      trip.id = index;
      trip.launch = element.launch;
      trip.status = element.status;
    }
    index++;
  });
});

      

+1


source


Array.of(response.val()).forEach

should work if it's just a massive object that lacks its iterator

0


source







All Articles