Skip to content

Instantly share code, notes, and snippets.

@yairEO
Last active November 10, 2020 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yairEO/9f7cc9dcb8a3adbafc86cc674b47350f to your computer and use it in GitHub Desktop.
Save yairEO/9f7cc9dcb8a3adbafc86cc674b47350f to your computer and use it in GitHub Desktop.
Deep Objects Merge (extending)
function extend( o, o1, o2) {
if( !(o instanceof Object) ) o = {};
copy(o, o1);
if( o2 )
copy(o, o2)
function copy(a,b){
// copy o2 to o
for( var key in b )
if( b.hasOwnProperty(key) ){
if( isObject(b[key]) ){
if( !isObject(a[key]) )
a[key] = Object.assign({}, b[key])
else
copy(a[key], b[key])
continue;
}
if( isArray(b[key]) ){
a[key] = (isArray(a[key]) ? a[key] : []).concat(b[key])
continue;
}
a[key] = b[key]
}
}
return o
}
function isArray(a){
return a instanceof Array
}
function isObject(obj) {
var type = Object.prototype.toString.call(obj).split(' ')[1].slice(0, -1);
return obj === Object(obj) && type != 'Array' && type != 'Function' && type != 'RegExp' && type != 'HTMLUnknownElement';
}
@yairEO
Copy link
Author

yairEO commented Nov 10, 2020

var TEST = {a:1, b:{a:1, b:2, c:3}}

console.log(   extend({}, TEST , {a:[{foo:2}, 111], b:{a:55,  c:{a:[111]}, d:1, e:2  }})   )

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