Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
// smashless version
/**
* Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
* @param obj1
* @param obj2
* @returns obj3 a new object based on obj1 and obj2
*/
function merge_options(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}
// jQuery?
// merge options object into settings object
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);
// now the content of settings object is the following:
// { validate: true, limit: 5, name: "bar" }
// smashless
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
/* merge defaults and options, without modifying defaults */
var settings = $.extend({}, defaults, options);
// the content of settings variable is now the following:
// {validate: true, limit: 5, name: "bar"}
// defaults and options variable remained the same
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment