How to Deep Clone JavaScript Object
Deep Cloning JavaScript object can be very simple or difficult depend on how complicate your object structure is. For an object with basic data types, a one liner code is all you need. But if there are functions or complex data types involved, then you should consider using libraries.
Snippet 1 (jQuery method)
This method use jQuery extend function which merge the contents of two or more objects together. This is the most reliable deep clone method without data loss or corruption.
let newObject = $.extend(true,{}, oldObject);
Snippet 2 (JSON)
This is the quickest way to deep clone objects that do NOT have functions, Date variables or other complex types such as ImageDatas, Blobs, FileLists, Maps, etc.
let newObject = JSON.parse(JSON.stringify(oldObject));
Snippet 3 (Structured Clone)
This is a hack of history.pushState() and history.replaceState() This is a synchronous clone and not recommended due to poor performance and probability to freeze the browser.
const structuredClone = obj => { const oldState = history.state; history.replaceState(obj, null); const clonedObj = history.state; history.replaceState(oldState, null); return clonedObj; }; let newObject = structuredClone(oldObject);
Snippet 4 (ES6 Shallow Clone)
Since deep clone JavaScript object natively can be difficult or has poor performance. If you don’t mind a shallow copy, here is ES6 code snippet that can do the trick in one line.
let newObject = Object.assign({}, oldObject);