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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay