How to safely access deeply nested object in Javascript
Khoa Pham

Khoa Pham @onmyway133

About: My apps https://onmyway133.com/apps/

Joined:
May 29, 2017

How to safely access deeply nested object in Javascript

Publish Date: Sep 3 '19
9 2

An object 's property can be null or undefined.

Accessing step by step is tedious

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

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

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 2 total

  • Sebastian Vargr
    Sebastian VargrSep 3, 2019

    Just make sure to use the import like in the above. :)

    I've unfortunately seen waaay to many projects include the entire lodash library for just one or two functions...

    Or even worse for already poly-filled array methods.. :D

Add comment