karan kalimi
karan kalimi

Reputation: 23

Cannot read property 'forEach' of undefined in reactjs application

I have a JS method that takes a JSON file and try to get information out of it:

getData(json) {
        var output = '';

        json.Legs.forEach(function (item) {
            .
            .
            .
            .
            .
            .
        });

        return output;
    }

I am getting this error for forEach:

Uncaught TypeError: Cannot read property 'forEach' of undefined

Is it possible to use forEach like this or I shouldn't be using forEach at all? Is there nother way to do this?

Upvotes: 0

Views: 10780

Answers (3)

Goran Gjorgievski
Goran Gjorgievski

Reputation: 77

Something like this should do the trick (check whether .legs property exists and whether its an array before iterating):

getData(json) {
    var output = '';

    if(json.Legs && Array.isArray(json.Legs)){

     json.Legs.forEach(function (item) {
        //do something with item
     });
    }

    return output;
}

Upvotes: 0

Abdul Qayyum
Abdul Qayyum

Reputation: 1052

You need to execute loop after confirming that json.Legs is not null. e.g

if(json.Legs){
  json.Legs.forEach(function (item) {
            .
            .
            .
            .
            .
            .
        });
}

Upvotes: 2

curlyBraces
curlyBraces

Reputation: 1105

Add this as the first line in the code and see what it prints. If it is an array you can all forEach on it. Otherwise it's throwing the right error.

console.log(json.Legs)

Upvotes: 0

Related Questions