How to safely access deeply nested object in Javascript

Issue #390

An object ‘s property can be null or undefined.

Accessing step by step is tedious

1
2
3
4
props.user &&
props.user.posts &&
props.user.posts[0] &&
props.user.posts[0].comments

Dynamic parsing path is too clever and involves string in the end, which is a no no

1
2
3
4
const get = (p, o) =>
p.reduce((xs, x) => (xs && xs[x]) ? xs[x] : null, o)

const getUserComments = get(['user', 'posts', 0, 'comments'])

Instead let’s use function and catch errors explicitly, and defaults with a fallback

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const get: (f, defaultValue) => {
try {
const value = f()
if (isNotNullOrUndefined(value)) {
return value
} else {
return defaultValue
}
} catch {
return defaultValue
}
}

const comments = get(() => { .user.posts[0].comments }, [])

Read more

Comments