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

Compile ES6 Code with Gulp and Babel, Part 3

In the third of five parts on compiling multiple ES6 files into a minified bundle, you will learn how to use a configuration file to build multiple dynamic manifest bundles.

Dec 19, 2018

How to Set Environment Variables in JavaScript Projects

Environment variables are a great way to store values that will change based on your program's context.

Aug 18, 2021