Skip to content

Instantly share code, notes, and snippets.

@muralikrishnat
Created June 5, 2020 21:41
Show Gist options
  • Save muralikrishnat/c06f0da68bf24b29fe9f57b3bc4da434 to your computer and use it in GitHub Desktop.
Save muralikrishnat/c06f0da68bf24b29fe9f57b3bc4da434 to your computer and use it in GitHub Desktop.
Object deep clone in Javascript
// Object deep clone
var deepClone = (src) => {
let objToReturn = {};
Object.keys(src).forEach(item => {
if (typeof src[item] === 'object' && !(src[item] instanceof Array)) {
objToReturn[item] = deepClone(src[item]);
} else {
if (typeof src[item] === 'object' && src[item] instanceof Array) {
objToReturn[item] = [...src[item]];
} else {
objToReturn[item] = src[item];
}
}
});
return objToReturn;
};
// Example
var obj = {
x: {
h: {
j: {
u: {
e: {
r: 10
}
}
},
k: {
t: {
w: [1, 2, 3, 4]
}
}
}
}
};
var obj2 = deepClone(obj);
obj2.x.h.k.t.w.push(5);
console.log("obj2", obj2.x.h.k.t.w, obj2.x.h.j.u.e.r);
// (5) [1, 2, 3, 4, 5] 10
console.log("obj", obj.x.h.k.t.w, obj.x.h.j.u.e.r);
// [1, 2, 3, 4] 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment