Skip to content

Instantly share code, notes, and snippets.

@briancavalier
Created December 3, 2014 16:26
Show Gist options
  • Select an option

  • Save briancavalier/c7f110ac65ce7b186f81 to your computer and use it in GitHub Desktop.

Select an option

Save briancavalier/c7f110ac65ce7b186f81 to your computer and use it in GitHub Desktop.
Recursively clone a JS Object or Array
module.exports = clone;
function clone(x) {
if(x == null || typeof x !== 'object') {
return x;
}
if(Array.isArray(x)) {
return cloneArray(x);
}
return cloneObject(x);
}
function cloneArray (x) {
var l = x.length;
var y = new Array(l);
for (var i = 0; i < l; ++i) {
y[i] = clone(x[i]);
}
return y;
}
function cloneObject (x) {
var keys = Object.keys(x);
var y = {};
for (var k, i = 0, l = keys.length; i < l; ++i) {
k = keys[i];
y[k] = clone(x[k]);
}
return y;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment