Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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){
            console.log(element);
        });
    }
});

I get the error that for each does not work on the data variable. However, when I log data to the console, I get

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

This is clearly an array and iterable, so I don't get what exactly is wrong.

EDIT: data is returned via JsonResponse in Django.

like image 955
absolutelydevastated Avatar asked Nov 13 '18 06:11

absolutelydevastated


2 Answers

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);
    });
}
like image 157
Mamun Avatar answered Nov 20 '22 15:11

Mamun


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);
        });
like image 2
Negi Rox Avatar answered Nov 20 '22 16:11

Negi Rox