Created
May 15, 2017 09:34
-
-
Save willwright82/5f5f9373cbcd6f532a251b580f8f13b2 to your computer and use it in GitHub Desktop.
Using Javascript to access deeply nested properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Access "hello" in: | |
var state = { prop1: { prop2: "hello" } }; | |
// Simple solution creating temporary variables: | |
var a = state && state.prop1 && state.prop1.prop2 | |
// a = "hello" | |
// Elegant solution: | |
var a = ((state || {}).prop1 || {}).prop2 | |
// a = "hello" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment