jQuery getObject: get.and.set.deep.objects.easily = true;


jQuery getObject allows you to get and set properties of an object via dot-delimited name string. Inspired by the Dojo methods of the same names.

Note for non-jQuery users

jQuery isn’t actually required for this plugin, because nothing internal uses any jQuery methods or properties. jQuery is just used as a namespace under which these methods can exist.

Since jQuery isn’t actually required for this plugin, if jQuery doesn’t exist when this plugin is loaded, the methods described below will be created in the Cowboy namespace. Usage will be exactly the same, but instead of $.method() or jQuery.method(), you’ll need to use Cowboy.method().

Note for Dojo users

The setObject, getObject, and exists methods are similar to their Dojo counterparts, with the exception that exists returns true or false based on whether or not a property is defined, not whether it is truthy.

Usage Examples

This plugin is useful if you have deep namespaces or data structures and don’t want to do excessive testing like: if ( a && a.b && a.b.c ) { ... } every time you need to get or set a property or invoke a method.

If that’s you, check out the examples below, and enjoy!

If that’s not you, check out something more exciting, like jQuery doTimeout or jQuery BBQ.

var myObj = {};

// Setting.
$.setObject( 'a.b.c', { d: 1, e: 2 }, myObj ); // returns a.b.c reference

// myObj is now { a: { b: { c: { d: 1, e: 2 } } } }

// Getting.
$.getObject( 'a.b.c.d', myObj ); // returns 1
$.getObject( 'a.b.c.x', myObj ); // returns undefined
$.getObject( 'a.b.c.d.x', myObj ); // returns undefined

// Testing.
$.exists( 'a.b.c.d', myObj ); // returns true
$.exists( 'a.b.c.x', myObj ); // returns false
$.exists( 'a.b.c.d.x', myObj ); // returns false

// I'm not sure why you'd want to do something like this, but it's
// certainly possible...
$.setObject( 'document.body.style.display', 'none' );
$.getObject( 'document.body.style.display' ); // returns 'none'

Please check out the documentation for specific usage information.

If you have any non-bug-related feedback or suggestions, please let me know below in the comments, and if you have any bug reports, please report them in the issues tracker, thanks!

Post A Comment

  • Any of these HTML tags may be used for style: a, b, i, br, p, strong, em, pre, code.
  • Multi-line JavaScript code should be wrapped in <pre class="brush:js"></pre>
    (supported syntax highlighting brushes: js, css, php, plain, bash, ruby, html, xml)
  • Use &lt; instead of < and &gt; instead of > in the examples themselves.