-2

here is my code:

useraccountprofileJSON.providerprofile.openinginfo.forEach(function(instance_1){
                                    instance_1.openingdetail.openingapplication.forEach(function(instance_2){
                                        console.log(instance_2);
                                        if(instance_2.oaid == oaid){
                                            isowner = true;
                                        }
                                    });
                                }); 

When I execute this I get the following error:

[TypeError: Cannot read property 'openingapplication' of undefined]

The error is because the last item(i.e last openingdetail) comes undefined in forEach iterations.

How to solve this?

Niyat patel
  • 23
  • 1
  • 7
  • Not include the `undefined` in your array (best solution), or simply check using `if(instance1){ ... }` – somethinghere Aug 17 '16 at 13:06
  • undefined is not in any of my values! – Niyat patel Aug 17 '16 at 13:08
  • But `forEach` is not _making it up_ either. It has to be there. Could you show the JSON and potentially the input / output of the JSON? – somethinghere Aug 17 '16 at 13:08
  • first `console.log()` your `instance_1` whether its getting `openingdetail` property or not. You are getting this undefined as `openingdetail` key is not available in your `instance_1`. – Ajitej Kaushik Aug 17 '16 at 13:10
  • @AjitejKaushik Yah, last item in instance_1 does not getting me openingdetail. Thats my point. Why isn't it showing me up even if its exists in database. It happens only to last item. – Niyat patel Aug 17 '16 at 13:17
  • It may happen that some of your collection may contain `openingdetail` and some may not, thatswhy you will may get this error, refer your tables and see there must be a conflict in data. – Ajitej Kaushik Aug 17 '16 at 13:24

1 Answers1

0

You can work around this, by replacing:

instance_1.openingdetail.openingapplication.forEach

with:

instance_1.openingdetail && instance_1.openingdetail.openingapplication.forEach

Remark

If the purpose of your code is just to set the isowner value, then you can use some, which will exit as soon as it finds one oid match:

isowner = useraccountprofileJSON.providerprofile.openinginfo.some(function(instance_1){
    return instance_1.openingdetail && 
           instance_1.openingdetail.openingapplication.some(function(instance_2){
        return instance_2.oaid == oaid;
    });
}); 
trincot
  • 317,000
  • 35
  • 244
  • 286