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

Generate Meta Images for Blog Posts with Node.js

Manually creating images for blog posts can be super time-consuming. Here's the foundation necessary for automatically generating meta images for content in markdown files.

Oct 08, 2021

Convert Markdown Image to HTML in VS Code

Make a bulk conversion of markdown images to HTML strings using a regex find and replace with VS Code.

May 03, 2022