forEach is not a function error

2020-07-24 05:43发布

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. :)

6条回答
ゆ 、 Hurt°
2楼-- · 2020-07-24 06:11

You cannot iterate objects using forEach, since it's an Array 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:

var keys = Object.keys(jBookedDates);

keys.forEach(function(key) {
    var item = jBookedDates[key];
    // Do your logic here
    // You will have access to the `key` variable and `item` variable
}

Using jQuery.each()

jQuery provides an improved forEach method, that works both with an jQuery collection, array or object.

$.each(function(key, item) {
   // Do your logic here
   // You also will have access to `key` and `item` variables
});

Many other Javascript frameworks/libraries provides an custom foreach method.

查看更多
smile是对你的礼貌
3楼-- · 2020-07-24 06:14

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.
});
查看更多
Luminary・发光体
4楼-- · 2020-07-24 06:15
Object.keys(a).forEach(elem => {  console.log(a[elem]) })
查看更多
何必那么认真
5楼-- · 2020-07-24 06:19

forEach only works on arrays, so if you want to iterate over an object you'll need to do:

for (var attr in obj) {
    // attr is your obj object attribute
    if (obj.hasOwnProperty(attr)) {
        // the magic goes here
    }
}
查看更多
Juvenile、少年°
6楼-- · 2020-07-24 06:23

how can i iterate over this object

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).

Object.keys(jBookedDates).forEach(function(key) {
  //jBookedDates[key] will give you the value for the current property
});

Please keep in mind that .forEach is actually Array.prototype.forEach. This means that the function is called on an array, not an object.

查看更多
地球回转人心会变
7楼-- · 2020-07-24 06:27

Why not just use for..in instead?

ex:

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

}

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.

查看更多
登录 后发表回答