Saturday, April 13, 2013

Javascript: Safely reading a nested property


In some templating frameworks it can be really annoying reading a nested property of a JS object as it can of mean chaining a heap of null checks together....

for instance if I need to access a nested property 'to' in 'email.addresses.to' safely it means having to do something like:

if(email && (adresses = email.addresses)) {
  //print addresses.to
}

This is verbose and annoying. I needed a function that would return the nested value, or simply return an empty string if any property in the chain was null or undefined

i.e.

safeRead(email, 'addresses', 'to');

I also wanted property chains can be as long or short as I'd like.... ie.:

safeRead(my, 'very', 'deeply', 'nested', 'property');

The finished product:


No comments: