Skip to content

Instantly share code, notes, and snippets.

@willwright82
Created May 15, 2017 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willwright82/5f5f9373cbcd6f532a251b580f8f13b2 to your computer and use it in GitHub Desktop.
Save willwright82/5f5f9373cbcd6f532a251b580f8f13b2 to your computer and use it in GitHub Desktop.
Using Javascript to access deeply nested properties
// 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