tags:

views:

22

answers:

2

When I parse JSON fields coming from google maps, etc., it is a mess. Because they are not made specifically for my script I have to verify many details, epecially because the addresses are different in every country.

Short question: when the script finds a undefined property the script breaks...error..

How can I verify the property is defined?

if(data.Placemark[i].AddressDetails.Country
       .AdministrativeArea.SubAdministrativeArea.Locality != null) {
         /***do something***/
}

Something like that doesn't seem to solve the problem. Why?

+3  A: 

In JavaScript, accessing a property of an object that does not exist returns undefined, not null - heck, you said it in the title.

So, assuming that all the previous properties do actually exist, you can check that the Locality property exists using typeof, like this:

if(typeof (data.
           Placemark[i].
           AddressDetails.
           Country.
           AdministrativeArea.
           SubAdministrativeArea.
           Locality) !== 'undefined') {
    /***do something***/
}

Or, (I think) you can use hasOwnProperty():

if (data.
    Placemark[i].
    AddressDetails.
    Country.
    AdministrativeArea.
    SubAdministrativeArea.hasOwnProperty('Locality'))
{
    /*** do something ***/
}
Matt Ball
also, as a self taught developer, is !== valid in JS? or is enough !=
camelCase
@camelCase: it's basically always better to use the strict versions (`===` and `!==`) rather than the type-coercing versions (`==` and `!=`).
Matt Ball
btw the error i get is "Cannot read property", so is not a problem of the value equal to 'undefined', but i guess the problem is that the property itself doesn't exist... i hope i was clear..
camelCase
@camelCase: see [this question](http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use) for details.
Matt Ball
@camelCase: have you ensured that **all** the previous properties exist? e.g. made sure that `data` has a `placemark` property, `placemark` has [whatever property `i` resolves to], etc?
Matt Ball
the .hasOwnProperty( ) WORKS!!!! easier than expected..as always happens, damn!
camelCase
@camelCase: all of the JS I know is self-taught as well. It just takes time and practice. And StackOverflow - **lots** of StackOverflow! :P
Matt Ball
A: 

First, In javascript you can use "try / catch" like java or other programming language, this can let your code continue running if something goes wrong...

for your issue, you can test that :

if (typeof(data.Placemark[i].AddressDetails.Country
               .AdministrativeArea.SubAdministrativeArea.Locality) 
    &&
      data.Placemark[i].AddressDetails.Country
               .AdministrativeArea.SubAdministrativeArea.Locality.length>0) {
}
Patrick Ferreira
The `Locality.length` check doesn't really make sense.
Matt Ball