Create and Retrieve Nested Objects with jQuery

By  on  

The ability to create and retrieve nested objects by objectified string path is incredibly useful.  Not only do you not need to do the manual string of object/property checks to avoid "{x} is not defined" errors, but if you create your method properly, you can also set an empty object in its given place (or namespace, some would call it.    Here's how you can add this functionality to the jQuery object.

The jQuery JavaScript

Since jQuery's philosophy is to use the same method for getting and setting, we'll be doing this same for creating and retrieving objects;  in this case, we'll use the obj method:

(function() {

	// Utility method to get and set objects that may or may not exist
	var objectifier = function(splits, create, context) {
		var result = context || window;
		for(var i = 0, s; result && (s = splits[i]); i++) {
			result = (s in result ? result[s] : (create ? result[s] = {} : undefined));
		}
		return result;
	};

	// Gets or sets an object
	jQuery.obj = function(name, value, create, context) {
		// Setter
		if(value != undefined) {
			var splits = name.split("."), s = splits.pop(), result = objectifier(splits, true, context);
			return result && s ? (result[s] = value) : undefined;
		}
		// Getter
		else {
			return objectifier(name.split("."), create, context);
		}
	};

})();

As with the MooTools alternative, the objectifier function is enough to handle both getting and setting, as well as doing both within a given context (existing object).  Here are a few examples of how you can use the new jQuery.obj method:

// Check for existence
var moduleNameExists = jQuery.obj("mynamespace.widget.moduleName"); // undefined

// Create the obj
jQuery.obj("mynamespace.widget.moduleName", { prop: 1 }); // mynamespace.widget.moduleName.prop returns 1

// Create an object on existing object
jQuery.obj("subnamespace.subModuleName", { someProp: 8 }, true, mynamespace.widget);
	// mynamespace.widget.subnamespace.subModuleName = { someProp: 8 }

As I work more with jQuery, both with its provided methods and other third party tools, accessing arbitrary objects by string and sometimes context allows me to avoid the dance of manual object and property existence checks.  Of course the essence of this script is really the objectifier method, which can be added to any framework or toolkit, but with a framework as popular as jQuery, why not just put it out there for everyone?

Recent Features

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

  • By
    9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

Incredible Demos

  • By
    Drag and Drop MooTools File Uploads

    Honesty hour confession:  file uploading within the web browser sucks.  It just does.  Like the ugly SELECT element, the file input is almost unstylable and looks different on different platforms.  Add to those criticism the fact that we're all used to drag and drop operations...

  • By
    CSS Vertical Centering

    Front-end developing is beautiful, and it's getting prettier by the day. Nowadays we got so many concepts, methodologies, good practices and whatnot to make our work stand out from the rest. Javascript (along with its countless third party libraries) and CSS have grown so big, helping...

Discussion

  1. Any chance that there is a demo or functional example of this available? I’m trying to use this to create nested dropdown boxes based on jQuery UI’s nested menu, and I’m having some difficulty understanding how to apply the objectifier function.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!