Javascript Default Options in Object

This article is about passing an object of options into your JavaScript functions, but at the same time having a set of default options with the exact same object properties.

Something like this:

function your_library(options) {
    var default_options = {
        "something": "value",
        "msg": {
            "m1": "test1",
            "m2": "test2"
        }
    };
}

your_library({"something": "new value"});

 

This is how you can go through all object properties (and any child objects) and in case one of the properties isn’t set use default option:

if (!options) {
    options = default_options;
}
else {
    function populate_options(object, default_object) {
        for (var op in default_object) {
            if (typeof object[op] === "undefined") {
                object[op] = default_object[op];
            }
            else if (typeof default_object[op] === "object") {
                populate_options(object[op], default_object[op]);
            }
        }
    }
    populate_options(options, default_options);
}

So basically what’s going on is we first ask if options exist at all, if not then just move all from default_options. If options exist then iterate through all properties and move any missing property from default_options.

Leave a Reply

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