Home

WTF is object-dig?

Tired of "Cannot read property of undefined" errors? object-dig can help!

object-dig is one of my favorite JavaScript libraries that isn't all that popular (I'll tell you why).

It provides a means of looking for a property in a deeply-nested object, without worrying about running into an error. Instead, the function will return undefined if any of the properties along the way don't exist.

It is inspired by Ruby's dig method, which provides similar functionality on Ruby hashes (which are /similar/ to JavaScript objects).

object-dig Example

For example, let's say we've imported the function as dig, like so:

import dig from "object-dig";

And we have a nested object:

const obj = {
a: {
b: {
c: "Hi there!",
},
},
};

I could access obj.a.b.c with dig:

dig(obj, ["a", "b", "c"]);
// => "Hi there!"

But if I tried a property that didn't exist and kept drilling, I'd just get undefined:

dig(obj, ["WRONG", "b", "c"]);
// => undefined

This is nice for avoiding an error just because a property doesn't exist.

I don't use object-dig today

All this said, as much as I love it, I don't use this function much today. If it's the type of functionality I require when working with objects, then I may include it. But I often make use of additional features from Lodash.

And Lodash has a get method which provides similar functionality, so I tend to opt for that.

Let's Connect

Keep Reading

WTF is Lodash?

Explore an introduction to Lodash and what it can do to support your JavaScript code.

Apr 21, 2020

How I Begin New JavaScript Projects

These are the first steps I take when I start a new JavaScript project.

May 26, 2021

10 Angular Tools to Build Creative Web Apps

To help the developers build robust and high-quality web apps, Angular offers plenty of useful tools.

Harikrishna Kundariya
Jun 30, 2022