最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read property 'forEach' of undefined in reactjs application - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Feb 6, 2018 at 8:41 karan kalimikaran kalimi 231 gold badge1 silver badge10 bronze badges 3
  • 2 error is pretty much clear, you do not have data within json.Legs. – Jigar Shah Commented Feb 6, 2018 at 8:43
  • JSON by definition does not have arbitrary properties as it is just a string. Do you mean a JavaScript object instead or do you pass a string? How do you call that function? – str Commented Feb 6, 2018 at 8:44
  • You need to run each loop after checking only if json.Legs is not null. e.g if(!json.Legs){ json.Legs.forEach(function (item) { . . . . . . }); } – Abdul Qayyum Commented Feb 6, 2018 at 8:45
Add a ment  | 

3 Answers 3

Reset to default 2

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

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

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)

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;
}
发布评论

评论列表(0)

  1. 暂无评论