Many times we need to do Deep copying objects in JavaScript. Since shallow copy may cause many issues as it may affect original object. Here are few ways to achieve same.
Table of Contents
1. Using JSON.parse(JSON.stringify(object));
var obj = { a: 1, b: { c: 2 } } var newObj = JSON.parse(JSON.stringify(obj)); obj.b.c = 20; console.log(obj); // { a: 1, b: { c: 20 } } console.log(newObj); // { a: 1, b: { c: 2 } }
2. Using created method
function cloneObject(obj) { var clone = {}; for(var i in obj) { if(obj[i] != null && typeof(obj[i])=="object") clone[i] = cloneObject(obj[i]); else clone[i] = obj[i]; } return clone; } var obj = { a: 1, b: { c: 2 } } var newObj = cloneObject(obj); obj.b.c = 20; console.log(obj); // { a: 1, b: { c: 20 } } console.log(newObj); // { a: 1, b: { c: 2 } }
3. Using Lo-Dash’s _.cloneDeep
var obj = { a: 1, b: { c: 2 } } var newObj = _.cloneDeep(obj); obj.b.c = 20; console.log(obj); // { a: 1, b: { c: 20 } } console.log(newObj); // { a: 1, b: { c: 2 } }
4. Using structuredClone()
var obj = { a: 1, b: { c: 2 } } const myDeepCopy = structuredClone(obj); obj.b.c = 20; console.log(obj); // { a: 1, b: { c: 20 } } console.log(myDeepCopy); // { a: 1, b: { c: 2 } }
Below approaches will not work with nested object but work for simple object.
5. Using Object.assign() method
var obj = { a: 1, b: 2 } var newObj = Object.assign({}, obj); // Object.assign(target, source) obj.b = 20; console.log(obj); // { a: 1, b: 20 } console.log(newObj); // { a: 1, b: 2 }
6. Using spread operator
var obj = { a: 1, b: 2 } var newObj = {...obj} obj.b = 20; console.log(obj); // { a: 1, b: 20 } console.log(newObj); // { a: 1, b: 2 }
7. Using Underscore.js _.clone
var obj = { a: 1, b: 2 } var newObj = _.clone(obj); obj.b = 20; console.log(obj); // { a: 1, b: 20 } console.log(newObj); // { a: 1, b: 2 }