Safely Read & Write in Deeply Nested Objects in Javascript

Gabin Desserprit
Data Hunter’s Blog
4 min readAug 9, 2017
Photo by Dan Gold on Unsplash

As I play with datasets I oftenly make Classes to properly work with my Objects. I can then add nifty functions to each Class and share them all accross my project easily.

Some time ago as I was playing with some pretty deeply nested objects I decided to make two ‘magic’ functions getValue() and setValue(). As always, the idea was to shorten my code and simplify my life. They would go into the object and check, step-by-step, if the sub-property exists until they reach the seeking one and then either gets its value either sets a new value.

These functions are part of a homemade library which works similarly to the famous lodash but implements functions (for objects, arrays, stings, datetime, operations, random, transform, types checks, etc) that I need on a daily basis.

Also as I wrote examples for this article I found out a pretty cool and more complete lib that will replace the core part of my functions. Stay calm, it’s coming.

Edit: Code examples links have been updated. Weirdly Medium won’t show new updates even when linked properly.

Pro Tip: Check out the examples on JsFiddle insted for better visibility and in your Node.js console for testing.

In which case?

Let’s take a dumb “deeply” nested object. I made that one as an example but imagine it could be any kind of data you’re working with (with way more nested data).

Let’s say that I wanted to get the our.adventure.name .

As you can quickly see, this is not set at all. You would end up with an Undefined result.

Now, let’s say we would like to set the our.adventure.name.text property (when even our.adventure.name doesn’t exists).

As expected, it won’t let us set a text property to an undefined object name which should be part of our.adventure object.

What would be the solution?

As you can imagine, the solution would be to recursively test if each property of the object exists and is an object (excepted for the last one presumably) so we can go deeper to get or set the value.

What is the solution?

Well as I like to do it when I’ve got some free time, I developped my own algorithm (but you’ll see that it’s not especially the path to follow).

First let’s make our functions. We need getValue(propertyPath, obj) and setValue(propertyPath, value, obj) .

The function getValue() takes a propertyPath (like adventure.name.text , and not our.adventure.name.text ) and an obj wich is the object from where we will get the value (and apply the property path).

The function setValue() takes the same previous arguments plus one : the value to set.

Handcoded or what?

Ok so, you’ll need to:

  • code an efficient object path parser (you know, to reach the property. Think about all the things that you would need to handle: arrays, dots in keys, etc).
  • be able to write recursive functions *function that calls itself (Not that difficult to make but still, it really depends your level)
  • properly handle the type checking (for object, array, string, number, null)

If you’ve read everything from the beginning you know that is what I firstly did. Let’s decompose a bit how that would fit in vanilla javascript.

I made the setValue() function and let you imagine how the getValue() would look (well, it’s really almost the same thing ;) ).

So we made our nifty function but as you’ve seen we don’t really check for value type or obj type and the propertyPath parsing is the most basic one (splitting on dots).

The code above is a simpler version of what I had done. But nevermind, I found for you THE package you’ll need object-path, a simple utility to access object through a path.

I let you dig into their examples here for more information.

Using the library, our code will now look as follow:
(I’m using Node.js here but you can use it in the Browser too)

Using it in a class

Oh yeah, this where the magic happens.

Now we are able to make a getSetValue() function to shorten even more your code. Meaning that if a value is passed, you will set it and if not, we will get the actual value.

You can now easily create methods/functions in your class to request value from your object.

Let’s imagine an Adventure Class and some methods to access its deeply hidden properties. Here in the example we only are outputing the value but you could imagine use them into other methods of your class to build more complex functions.

Wait but this looks neet but how would it have been if it wasn’t factored?

Ok, let met right only one method, the this.isOnItsWayOrWeMayStillEndUpInATrap one.

I know, I know. This looks bad. Reaaaaaally bad. Let me know by the way how you would solve this. I wrote it in the most naïve way in the example :)

Conclusion

Coding is fantastic but making it right isn’t easy. I truelly hope this brief insight on how I handle deep nested properties in Javascript Objects (and so JSON too) will show you that factoring your code is great and taking a little bit more time to factor it properly, even better :)

Feel free to comment, like & share. I’m here!

I’m Gabin, Data Hunter (Scraping & Web Automation & more)
Let’s talk on datahunter.pro

--

--