Skip to content

Instantly share code, notes, and snippets.

@morphar
Last active December 22, 2015 17:49
Show Gist options
  • Save morphar/6508914 to your computer and use it in GitHub Desktop.
Save morphar/6508914 to your computer and use it in GitHub Desktop.
Deep cloning of objects in javascript
/**
example:
var params = { fullText: { abc: '123' }, test1: { $in: [1,2,3] }, test2: { $in: ['a','b','c'] } };
var filter = clone(params);
delete filter.fullText;
params.test1.$in[1] = 5;
params.test2.$in[1] = 'x';
console.log(params);
console.log(filter);
*/
var clone = function(obj) {
if((this instanceof clone) == false) {
return new clone(obj);
}
for(i in obj) {
if(typeof(obj[i]) == 'object') {
if(Object.prototype.toString.call(obj[i]) === '[object Array]') {
this[i] = obj[i].slice();
} else {
this[i] = new clone(obj[i]);
}
} else {
this[i] = obj[i];
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment