Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 863
eat-sleep-code Avatar asked Dec 07 '22 18:12

eat-sleep-code


2 Answers

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

not realy foreach, but works exactly like it

but you also can use map functions

like image 170
TypedSource Avatar answered Mar 23 '23 00:03

TypedSource


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

like image 36
Ahmed Musallam Avatar answered Mar 22 '23 23:03

Ahmed Musallam