Skip to content

Instantly share code, notes, and snippets.

@kieraneglin
Last active February 28, 2019 13:01
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kieraneglin/12a3edbddb0c2bda742010eb95ea4fb3 to your computer and use it in GitHub Desktop.
Save kieraneglin/12a3edbddb0c2bda742010eb95ea4fb3 to your computer and use it in GitHub Desktop.
Safely Access Deeply Nested Objects In JavaScript
// Problem: how do you access a deeply nested object that you're not certain exists?
// if(object.user && object.user.post && object.user.post[0] && object.user.post[0].comment) {
// return object.user.post[0].comment
// }
// and that's horrifying. Here's something better
const idx = (props, object) => props.reduce((prefix, val) => (prefix && prefix[val]) ? prefix[val] : null, object)
// Usage:
nestedObj = {...}
idx(['object', 'user', 'post', 0, 'comment'], nestedObj) // Returns associated value or null
@manusisnova
Copy link

Work great thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment