How to create a deep copy of an object in JavaScript/TypeScript
Thu, 25 Feb 2021 00:00 UTC 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
-
Web Analytics
-
.NET
-
API Versioning and Basic UI Authentication with OpenAPI (Swagger / Swashbuckle) in .NET Core 6
-
Converting Enum Types By Value in C#
-
Implementing Microsoft.Extensions.Logging.ILogger with NLog
-
ASP.NET File Uploader with SignalR Progress Bar and Extended Input Stream Processing
-
How to inject Google Adsense In-Article script into your HTML (ASP.NET Core Razor)
-
Robust Error Handling in ASP.NET Core
-
A Utility Class for Finding Database Deadlocks in .NET Applications
-
Sanitizing HTML in .NET Core
-
Uploading Directly to S3 from Client Using Pre-Signed URLs (JavaScript, .NET)
-
Including Automated Swagger Documentation for API Dependencies
-
API Versioning and Basic UI Authentication with OpenAPI (Swagger / Swashbuckle) in .NET Core 6
-
Principles
-
JavaScript & TypeScript
-
AI
-
Software Architecture
-
General
-
Docker