Skip to content

Instantly share code, notes, and snippets.

@CharlesAnifowose
Last active January 1, 2016 22:09
Show Gist options
  • Save CharlesAnifowose/8208577 to your computer and use it in GitHub Desktop.
Save CharlesAnifowose/8208577 to your computer and use it in GitHub Desktop.
Similar intention as Underscore's _.defaults() algorithm, but with the ability to go deep into objects. Function will error out if Objects have circular references. Dependencies: UnderscoreJS
function deepDefault(obj, source, depth, blankCheck){
if (depth===undefined){
depth=0;
}
if (depth>1000){
throw new Error('Too many iterations, possible circular reference');
return;
}
_.each(source, function(sourceVal, i){
var val = obj[i];
if (_.isFunction(val)){
// do nothing
}
else if (_.isObject(val)){
if( _.isObject(sourceVal) && !_.isFunction(sourceVal) ){
deepDefault(val, sourceVal, depth+1, blankCheck);
}
}
else if (val===undefined){
if( _.isObject(sourceVal) && !_.isFunction(sourceVal) ){
obj[i]={};
deepDefault(obj[i], sourceVal, depth+1, true);
}
else{
obj[i] = sourceVal;
}
}
})
}
var a = {dog:'woof', cat:{sleepy:'purr'} };
var b = {mouse:'squeak', cat:{awake:'meow'}};
deepExtend(a,b);
console.log(a);
// {dog:'woof', cat:{sleepy:'purr', awake:'meow'}, mouse:'squeak'}
@CharlesAnifowose
Copy link
Author

Had to be careful with the functions that look like objects!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment