0

I'm Working on search form were i need to check whether city is empty or not. If it is empty then assign Bangalore to it other show the selected city. Here is my If condition

if(this.locations[0].city!="")
{
   var Dynamic = this.locations[0].city;
}
else
{
   Dynamic = "Bangalore";
}

But getting

Runtime Error. cannot read property '0' of undefined.

I am new to Ionic 2.

James Z
  • 12,209
  • 10
  • 24
  • 44
user1624540
  • 91
  • 10

3 Answers3

1

modify the IF condition like the below

 if(this.location!=undefined && this.location.length!=0 && this.locations[0].city!="")
    {
       var Dynamic = this.locations[0].city;
    }
    else
    {
       Dynamic = "Bangalore";
    }
Prithivi Raj
  • 2,658
  • 1
  • 19
  • 34
1

I might do this

var Dynamic = "Bangalore";
' first to are verifying they are defined
if(this.locations && this.locations[0] && this.locations[0].city && this.locations[0].city.length > 0)
{
  Dynamic = this.locations[0].city;
}
Philip Brack
  • 1,340
  • 14
  • 26
0

I suggest you create a function called checkNested for checking the validity of a nested object and use it throughout your app. You can put that in a service.

Also, I think you should define Dynamic outside of the if statement for scoping reasons.

var Dynamic = "Bangalore";
if(this.locations &&  // Checking if this.locations is valid before indexing it
   this.checkNested(this.locations[0], "city") && 
   this.locations[0].city !="" ){
   Dynamic = this.locations[0].city;
}

checkNested function is defined here.

Ari
  • 7,251
  • 11
  • 40
  • 70