Recursive object merge with $.extend()


This post comes as an addition to this article:
Coding with a purpose: jquery $.extend() and $.fn.extend() confusion

As recommended in a jQuery plugin structure, I have a separate “default” object ($.fn.myplugin.defaults) which holds my default values for the plugin.
I then merge this object in the main function with a “configuration” object passed in when instantiating the plugin, the later being meant to overwrite the defaults.
The operation happens fine as long as your objects are 1 level deep.
But in case you would like, as in the example bellow to overwrite only one value down the tree, you will have to set the first optional argument (deep) to true, as explained in the $.extend() documentation

/* Instantiation of my plugin */
$(document).ready( function() {
	$("#someId").jQPlugin({
		//pass the configuration object:
		name: {
			last: {"Martin"}
		}
	}
});

/* Plugin definition */
(function($) {
	$.fn.jQPlugin = function(configuration) {
		return this.each(function() {
				//first option to true here:
		var opts = $.extend(true, {}, $.fn.jQPlugin.defaults, configuration);
		}
	}
}
$.fn.jQPlugin.defaults = {
	age: {14},
	name: {
		first: {"John"},
		last: {"Doe"}
}

‘opts’ becomes :

opts = {
	age: {14},
	name: {
		first: {"John"},
		last: {"Martin"}
	}
}

instead of:

opts = {
	age: {14},
	name: {
		last: {"Martin"}
	}
}

, ,

Comments are closed.