eat-sleep-code
eat-sleep-code

Reputation: 4875

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

I am trying to port some of my Firebase database calls to an IOT board that does not have jQuery, just good old JavaScript.

In my code I originally had a jQuery $.each(tripData, function(index, element) ... loop to iterate through my results.

I have 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 am not sure how to resolve this.

Upvotes: 4

Views: 6731

Answers (4)

Frank van Puffelen
Frank van Puffelen

Reputation: 600126

While the answer by @TypedSource will iterate over the resulting children, the order in which it iterates is undetermined - and very likely not going to be by timestamp.

A snapshot that you get as the result for a query contains three pieces of information for each child: its key, its value, and its position relative to the other children. When you call .val() on the snapshot, you lose the relative ordering.

To maintain the order, use the built-in forEach() method of the snapshot:

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++;
  });
});

Upvotes: 2

Ahmed Musallam
Ahmed Musallam

Reputation: 9753

You should really figure out if your response is an Array or Object. $.each() iterates over arrays AND objects, thats why it works.

you should use for...in statement if you really want to iterate over this object tripData.

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

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

Upvotes: 4

roberto tomás
roberto tomás

Reputation: 4697

Array.of(response.val()).forEach should work if it is just an array-like object missing its iterator

Upvotes: 0

TypedSource
TypedSource

Reputation: 708

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

not realy foreach, but works exactly like it

but you also can use map functions

Upvotes: 9

Related Questions