Skip to content

Instantly share code, notes, and snippets.

@jumbojett
Last active August 29, 2015 14:07
Show Gist options
  • Save jumbojett/4758b23b693dacfbee4d to your computer and use it in GitHub Desktop.
Save jumbojett/4758b23b693dacfbee4d to your computer and use it in GitHub Desktop.
javascript test for existence of nested object key and assign it

Sometimes you need to check for a nested object value and assign it if it exists.

Please note the following ugly code.

var assign_to_this;
if(test.level1 && test.level1.level2 && test.level1.level2.level3) {
    assign_to_this = test.level1.level2.level3;
}

Can be re-writen in a minmalistic way.

var assign_to_this = (((test || {}).level1 || {}).level2 || {}).level3;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment