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

2 Ways to Keep JavaScript Local

It's far too easy to let your JS code pollute the global namespace. Here are two methods for keeping your code local.

May 21, 2018

Simplify Components by Separating Logic from Presentation using Adapters

It's tough to know when it's the right time to break a component up into smaller components. Here's a way to approach that process that relies on more than what you see on the screen.

Jul 10, 2020