Created
September 25, 2019 22:08
-
-
Save rodmoioliveira/b24e933d02ae9b03b85cbbbca15130cd to your computer and use it in GitHub Desktop.
Safely Accessing Deeply Nested Values In JavaScript
This file contains hidden or 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
| // https://medium.com/javascript-inside/safely-accessing-deeply-nested-values-in-javascript-99bf72a0855a | |
| const props = { | |
| user: { | |
| posts: [ | |
| { title: 'Foo', comments: ['Good one!', 'Interesting...'] }, | |
| { title: 'Bar', comments: ['Ok'] }, | |
| { title: 'Baz', comments: [] }, | |
| ] | |
| } | |
| } | |
| const get = (path, fallback = null) => object => | |
| path.reduce((acc, cur) => (acc && acc[cur] ? acc[cur] : fallback), object); | |
| console.log(get(['user', 'posts', 0, 'log'])(props)); | |
| // => null | |
| console.log(get(['user', 'posts', 0])(props)); | |
| // => { title: 'Foo', comments: ['Good one!', 'Interesting...'] } | |
| console.log(get(['user', 'posts', 2, 'comments', 2], 'another value')(props)); | |
| // => another value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment