Skip to content

Instantly share code, notes, and snippets.

@rodmoioliveira
Created September 25, 2019 22:08
Show Gist options
  • Select an option

  • Save rodmoioliveira/b24e933d02ae9b03b85cbbbca15130cd to your computer and use it in GitHub Desktop.

Select an option

Save rodmoioliveira/b24e933d02ae9b03b85cbbbca15130cd to your computer and use it in GitHub Desktop.
Safely Accessing Deeply Nested Values In JavaScript
// 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