Robert Ross Robert Ross - 14 days ago 5
Ajax Question

forEach is not a function error

I get this error when I am trying to iterate through my JSON object with a foreach.
Can someone help, please?

Here is my JS:

function dateTimeChecker() {
$.ajax({
"url": 'get-booked.php',
"method": "get",
"dataType": "text",
"cache": false
}).done(function(jBooked) {
var jBookedDates=JSON.parse(jBooked);
console.log(jBookedDates);
jBookedDates.forEach(function(jB){
if (jB=="11/01/2016") {console.log("works");}else{console.log("doesn't");}
})
});
}


And here is the object in question :

enter image description here

Also, I am wondering how can i iterate over this object if someone cares to explain. :)

Answer

The response that you are receiving is a JSON. You can't use an array object's method forEach over a plain object. You have to use Object.keys() at this context to retrieve the enumerable own properties belongs to the parsed JSON,

Object.keys(jBookedDates).forEach(function(jB){
 if (jB=="11/01/2016") {
    console.log("works");
 } else {
    console.log("doesn't");
 }
});

For your query in the comment, you can use bracket notation to access those arrays,

Object.keys(jBookedDates).forEach(function(jB){
  var arr = jBookedDates[jB];
  console.log(arr); //will print the array belongs to each property.
});