close

[Solved] TypeError: data.forEach is not a function

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error TypeError: data.forEach is not a function in javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How TypeError: data.forEach is not a function Error Occurs?

I am just using my API response in ForEach Loop But I am facing the following error.

TypeError: data.forEach is not a function

Here is My Code

$.ajax({
    url: "some_url/",
    type: "GET",
    dataType: "json",
    success: function(data){
        console.log(data);
        data.forEach(function(element){
            console.log(element);
        });
    }
});

How To Solve TypeError: data.forEach is not a function Error?

  1. How To Solve TypeError: data.forEach is not a function Error?

    To Solve TypeError: data.forEach is not a function Error I believe data is a JSON string. Since forEach() is an array function and you are trying to implement it on the JSON string it throws the error. You have to parse the data JSON.parse() before using forEach(). Example.

  2. TypeError: data.forEach is not a function

    To Solve TypeError: data.forEach is not a function Error I believe data is a JSON string. Since forEach() is an array function and you are trying to implement it on the JSON string it throws the error. You have to parse the data JSON.parse() before using forEach(). Example.

Solution 1

I believe data is a JSON string. Since forEach() is an array function and you are trying to implement it on the JSON string it throws the error. You have to parse the data JSON.parse() before using forEach(). Example.

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);
        });

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read

Leave a Comment