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

Use Netlify Functions to Send Email Notifications

Learn the basics of sending custom email notifications using Netlify functions and your email service of choice.

May 06, 2021

Create a Multi-Colored, Dotted Grid with HTML5 Canvas

The wide world of canvas is open-ended. Here's a fun example to dig in and learn some of the basics of HTML5 canvas.

Feb 26, 2016