I have a function which may be called with an optional object containing multiple options, each of which should fall back to a default value if omitted.
I'm currently doing this like so:
function f(options){
var _options = options || {};
_options.propertyOne = options.propertyOne || 50;
_options.propertyTwo = options.propertyOne || 100;
_options.propertyThree = options.propertyThree || {};
_options.propertyThree.subPropOne = options.propertyThree.subPropOne || 150;
//etc...
}
var options = {
propertyOne: 20,
propertyThree: {
subPropOne: 100
}
}
f(options);
However, as the number of options grows, the code is looking increasingly messy. There's also the potential problem of false/zero values being ignored (though all properties are currently numerical and non-zero).
Is there a more effective, more concise way of achieving this? I've considered creating an object initialised to default values within my function, then recursively copying any options supplied in the argument to it, but I'm not sure if doing so could introduce new problems that I haven't thought of yet.
Edit:
The function I would use to recursively copy properties:
function copyOptions(from, to){
for(var i in from){
if(typeof from[i] == "object"){
to[i] = copyOptions(from[i], to[i]);
}else if(typeof from[i] != "undefined"){
to[i] = from[i];
}
}
}