Last active
February 28, 2019 13:01
-
-
Save kieraneglin/12a3edbddb0c2bda742010eb95ea4fb3 to your computer and use it in GitHub Desktop.
Safely Access Deeply Nested Objects In JavaScript
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
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Work great thanks!!