Most use of $.extend, a cleaner way

Written by Yannik Messerli - 17 March 2015


Most of the time, you would use $.extend to override some default options in a plugin to create settings, e.g.

var defaults = { a: 3, b: 6}
var settings = $.extend({}, defaults, {a: 4});

In order to be sure to have a and b in your settings object all the time. However, it doesn't prevent to have also c, e.g.

var settings = $.extend({}, defaults, {a: 4, c: 8});

Sometimes, you need exactly a and b. Here is a snippet to copy values of a javascript object for properties that exist in the source object, without adding other properties:

var assign = function(destination){
        for (var i = 1; i < arguments.length; i++) {
            var source = arguments[i];
            for(var prop in destination){
                if(typeof(destination[prop]) === "object" && source[prop]){
                    assign(destination[prop], source[prop]);
                }else{
                    if(source[prop]){
                        destination[prop] = source[prop];
                    }
                }
            }
        }
        return destination;
    }

Now, settings has only a and b:

var settings = assign(defaults, {a: 4, c: 8}, {d: 3});


Note: useful when storing or sending the data and keep it to the minimal

Note: here I'm modifying directly defaults. Consider copy it before

Written by

Yannik Messerli

Comments