javascript-deep-clone-object
Javascript

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);
Note
$.extend({}, oldObject) returns a shallow copy object and can’t be used. The first argument “true” force a recursive merge (known as Deep copy)
Note
Not to be confused with jQuery.clone() as this function works with DOM elements only

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);

Leave a Reply

Your email address will not be published. Required fields are marked *

error: