I have a function that takes a config
object as an argument. Within the function, I also have default
object. Each of those objects contains properties that essentially work as settings for the rest of the code within the function. In order to prevent having to specify all of the settings within the config
object, I use jQuery's extend
method to fill in a new object, settings
with any default values from the default
object if they weren't specified in the config
object:
var config = {key1: value1};
var default = {key1: default1, key2: default2, key 3: default 3};
var settings = $.extend(default, config);
//resulting properties of settings:
settings = {key1: value1, key2: default2, key 3: default 3};
This works great, but I'd like to reproduce this functionality without the need for jQuery. Is there an equally elegant (or close to) means to do this with plain ol' javascript?
This question is not a duplicate of the "How can I merge properties of two JavaScript objects dynamically?" question. Whereas that question simply wants to create an object that contains all of the keys and values from two separate objects - I specifically want to address how to do this in the event that both objects share some but not all keys and which object will get precedence (the default) for the resulting object in the event that there are duplicate keys. And even more specifically, I wanted to address the use of jQuery's method to achieve this and find an alternative way to do so without jQuery. While many of the answers to both questions overlap, that does not mean that the questions themselves are the same.
To get the result in your code, you would do:
function extend(a, b){
for(var key in b)
if(b.hasOwnProperty(key))
a[key] = b[key];
return a;
}
Keep in mind that the way you used extend there will modify the default object. If you don't want that, use
$.extend({}, default, config)
A more robust solution that mimics jQuery's functionality would be as follows:
function extend(){
for(var i=1; i<arguments.length; i++)
for(var key in arguments[i])
if(arguments[i].hasOwnProperty(key))
arguments[0][key] = arguments[i][key];
return arguments[0];
}