Skip to content

Instantly share code, notes, and snippets.

@cyrilf
Created June 5, 2018 08:38
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 cyrilf/0f71986a9d5c20ec2637022512d9c924 to your computer and use it in GitHub Desktop.
Save cyrilf/0f71986a9d5c20ec2637022512d9c924 to your computer and use it in GitHub Desktop.
// Utility function to get access nested object properties securely
//
// Usage:
// const invoiceName = get(account, "user.invoiceAddress.name")
//
// Instead of:
// const invoiceName = (account && account.user && account.user.invoiceAddress && account.user.invoiceAddress.name) || null
// https://stackoverflow.com/a/23809123/1410020
const get = (obj, key) =>
key
.split(".")
.reduce((o, x) => (typeof o == "undefined" || o === null) ? o : o[x], obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment