2

Let's say I have an object called John with many other nested objects inside and I am trying to access them following way

if (john.address.highstreet) {
    var highstreet = john.address.highstreet
}

but if address property is null, then I will get an error

unable to get property 'highstreet' of undefined

and my function execution stops

Is there a way of accessing nested properties without making many nested if statements like it's shown below:

if (john.address) {
    if (john.address.highstreet) {
        var highstreet = john.address.highstreet
    }
}

4 Answers4

6

The standard way would be

if (john.address && john.address.highstreet) {
    var highstreet = john.address.highstreet
}

If address is undefined then that is what will be returned.

Euan Smith
  • 2,102
  • 1
  • 16
  • 26
1

You probably want to use a bit more clever way of accessing these properties. Something like getPropertyByString("john.address.highstreet"). This function could return null or undefined if the path can't be resolved.

As in Alnitak's response

So your code could look just like this:

var highstreet = getPropertyByString("john.address.highstreet");
Community
  • 1
  • 1
strah
  • 6,702
  • 4
  • 33
  • 45
0

An alternative could be to use a try-catch-block.

try {
    var highstreet = john.address.highstreet;
} catch (err) {
    // do error handling
}
Andre
  • 385
  • 1
  • 13
0

You can also use hasOwnProperty method to check for property

if(john.hasOwnProperty("address") && john.address.hasOwnProperty("highstreet"))
{
var highstreet = john.address.highstreet
}
Satish Kumar sonker
  • 1,250
  • 8
  • 15