Skip to content Skip to sidebar Skip to footer

TypeError: Data.forEach Is Not A Function

This is my code: $.ajax({ url: 'some_url/', type: 'GET', dataType: 'json', success: function(data){ console.log(data); data.forEach(function(element

Solution 1:

I believe data is a JSON string. Since forEach() is a array function and you are trying to implement it on the JSON string it throws the error:

"Uncaught TypeError: data.forEach is not a function"

You have to parse the data with JSON.parse() before using forEach():

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

data = JSON.parse(data);

Demo:

var data = JSON.stringify([{"model": "app.mdl", "pk": 1, "fields": {"name": "test", "rank": 1}}]);
data = JSON.parse(data);
data.forEach(function(element){
    console.log(element);
});

So the success should be:

success: function(data){
    data = JSON.parse(data);
    console.log(data);
    data.forEach(function(element){
        console.log(element);
    });
}

Solution 2:

just check for either it is string or JSOn array

if(typeof(data) === "string"){data = JSON.parse(data)}
 data.forEach(function(element){
            console.log(element);
        });

Solution 3:

Just check if the data is JSON string.

data = "[{"model":"app.mdl","pk":1,"fields":{"name":"test","rank":1}}]"

if yes, the you have to do JSON.parse(data) and do forEach on it.


Solution 4:

It is a case where your data response looks like an array but it is a string. If you have access to the API you're connecting to you can ensure the response it sends out is an array but if not simply parsing the data response using JSON.parse() should do the trick.


Solution 5:

Change your success function to this, the JSON.parse() function is required to iterate over the JSON string:

success: function(data){
        data = JSON.parse(data);
        console.log(data);
        data.forEach(function(element){
            console.log(element);
        });

Post a Comment for "TypeError: Data.forEach Is Not A Function"