For software development and maintenance, contact me at contact@appsoftware.com or via appsoftware.com


How to create a deep copy of an object in JavaScript/TypeScript

Thu, 25 Feb 2021 by garethbrown

If you already know the difference between a deep and shallow copy of an object, then you don’t need to read the very good but quite long articles I got from my Google search on the most straight forward way to create a deep copy of an object in JavaScript/TypeScript.

Basically, do this:

let deepCopy = JSON.parse(JSON.stringify(objectToDeepCopy));

Here is a full working example, which you can play with on Codepen if you like.

let anArray = [
  { id: 1, name: 'Foo'},
  { id: 2, name: 'Bar'}
];

// Create shallow and deep copies of anArray

let shallowCopyOfArray = anArray;

let deepCopyOfArray = JSON.parse(JSON.stringify(anArray)); // <!-- Like this to create a deep copy!

// Log compare of instance equality

console.log('anArray is same object instance as shallowCopyOfArray', shallowCopyOfArray === anArray); // true

console.log('deepCopyOfArray is same object instance as shallowCopyOfArray', deepCopyOfArray === anArray); // false

The information provided on this Website is for general informational and educational purposes only. While we strive to provide accurate and up-to-date information, we make no warranties or representations, express or implied, as to the accuracy, completeness, reliability, or suitability of the content, including code samples and product recommendations, presented on this Website.

The use of any information, code samples, or product recommendations on this Website is entirely at your own risk, and we shall not be held liable for any loss or damage, direct or indirect, arising from or in connection with the use of this Website or the information provided herein.
UI block loader
One moment please ...