JavaScript Default Options

This article is about merging the contents of two objects together into the first object.
Use case is passing options to JavaScript function in an object, each option you send to the function overrides default option set inside the function itself.

This is the function that you need to include in your JavaScript file and call from your function:

function igorwarePopulateOptions(options, defaultOptions) {
    if (!options) {
        options = defaultOptions;
        return;
    }

    for (var option in defaultOptions) {
        if (typeof options[option] === "undefined") {
            options[option] = defaultOptions[option];
        } else if (typeof defaultOptions[option] === "object") {
            igorwarePopulateOptions(options[option], defaultOptions[option]);
        }
    }
}

Function goes through all properties of default_options, checks if property exists in options and overrides it if it does. If property does not exist in default_options and does exist in options it will not be copied. This function is recursive so you can have nested objects and it will work.

Example use:

function customFunction(options) {
    var defaultOptions = {
        "myOption": "value",
        "msg": {
            "m1": "test1",
            "m2": "test2"
        }
    };

    igorwarePopulateOptions(options, defaultOptions);

    // Test
    console.log(options);
}

customFunction({"myOption": "new value"});

This is the output of the console.log from the example above:

{
    myOption: "new value",
    msg: {
        m1: "test1",
        m2: "test2"
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *