DEV Community

Khoa Pham
Khoa Pham

Posted on

3 2

How to safely access deeply nested object in Javascript

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (2)

Collapse
 
sebbdk profile image
Sebastian Vargr • Edited

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs