Last Updated: February 25, 2016
·
465
· yannikmesserli

Most use of $.extend, a cleaner way

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});

<br/>

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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside