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 :
Also, I am wondering how can i iterate over this object if someone cares to explain. :)
You cannot iterate objects using
forEach
, since it's anArray
class method.There are some ways to iterate an Object:
Using Object.keys()
You use
Object.keys()
method to get your object keys then iterate over it:Using jQuery.each()
jQuery provides an improved
forEach
method, that works both with an jQuery collection, array or object.Many other Javascript frameworks/libraries provides an custom foreach method.
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 useObject.keys()
at this context to retrieve the enumerable own properties belongs to the parsed JSON,For your query in the comment, you can use bracket notation to access those arrays,
forEach only works on arrays, so if you want to iterate over an object you'll need to do:
You can't, but you can iterate over this object's properties. This would be done using
Object.keys()
, which returns an array filled with the object's properties (or keys).Please keep in mind that
.forEach
is actuallyArray.prototype.forEach
. This means that the function is called on an array, not an object.Why not just use for..in instead?
ex:
}
It is helpful not to always default to a jQuery solution. Understanding the mechanics of vanilla javascript will often solve a lot of problems for you that libraries cannot address without unneccessary complexity or revisions outside the area where the specific logic needs to be applied.