Skip to content
Fix Code Error

What is the most efficient way to deep clone an object in JavaScript?

March 13, 2021 by Code Error
Posted By: Anonymous

What is the most efficient way to clone a JavaScript object? I’ve seen obj = eval(uneval(o)); being used, but that’s non-standard and only supported by Firefox.

I’ve done things like obj = JSON.parse(JSON.stringify(o)); but question the efficiency.

I’ve also seen recursive copying functions with various flaws.

I’m surprised no canonical solution exists.

Solution

Native deep cloning

It’s called "structured cloning", works experimentally in Node 11 and later, and hopefully will land in browsers. See this answer for more details.

Fast cloning with data loss – JSON.parse/stringify

If you do not use Dates, functions, undefined, Infinity, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object, a very simple one liner to deep clone an object is:

JSON.parse(JSON.stringify(object))

const a = {
  string: 'string',
  number: 123,
  bool: false,
  nul: null,
  date: new Date(),  // stringified
  undef: undefined,  // lost
  inf: Infinity,  // forced to 'null'
  re: /.*/,  // lost
}
console.log(a);
console.log(typeof a.date);  // Date object
const clone = JSON.parse(JSON.stringify(a));
console.log(clone);
console.log(typeof clone.date);  // result of .toISOString()

See Corban’s answer for benchmarks.

Reliable cloning using a library

Since cloning objects is not trivial (complex types, circular references, function etc.), most major libraries provide function to clone objects. Don’t reinvent the wheel – if you’re already using a library, check if it has an object cloning function. For example,

  • lodash – cloneDeep; can be imported separately via the lodash.clonedeep module and is probably your best choice if you’re not already using a library that provides a deep cloning function
  • AngularJS – angular.copy
  • jQuery – jQuery.extend(true, { }, oldObject); .clone() only clones DOM elements

ES6 (shallow copy)

For completeness, note that ES6 offers two shallow copy mechanisms: Object.assign() and the spread syntax.
which copies values of all enumerable own properties from one object to another. For example:

var A1 = {a: "2"};
var A2 = Object.assign({}, A1);
var A3 = {...A1};  // Spread Syntax
Answered By: John Resig

Related Articles

  • error LNK2005: ✘✘✘ already defined in…
  • What's the difference between eval, exec, and compile?
  • How to find Control in TemplateField of GridView?
  • How to prevent scrolling the whole page?
  • Does moment.js allow me to derive a timezone…
  • How to properly do JSON API GET requests and assign…
  • How does the "this" keyword work?
  • How many times the loss function is triggered from…
  • Using Address Instead Of Longitude And Latitude With…
  • List of Timezone IDs for use with FindTimeZoneById() in C#?
  • typescript - cloning object
  • Google Maps: Set Center, Set Center Point and Set…
  • How to set zoom level in google map
  • how to turn a recursive algorithms into an iterative one
  • The 'compilation' argument must be an instance of…
  • NullpointerException error while working with…
  • DQN Pytorch Loss keeps increasing
  • labeling based on the character value of numerical…
  • error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or…
  • Memcached vs. Redis?
  • Why does my convolutional model does not learn?
  • How to Deep clone in javascript
  • How do I keep only the first map and when the game…
  • Ukkonen's suffix tree algorithm in plain English
  • How to print binary tree diagram?
  • Making Make Automatically Compile Objs from Headers…
  • Weights were not updated using Gradient Tape and…
  • Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)
  • How to print an AST from a parser generator to graphviz?
  • How do I correctly clone a JavaScript object?
  • What is the most efficient/elegant way to parse a…
  • How can I access and process nested objects, arrays or JSON?
  • JS Graph recursive vs iterative DFS order difference
  • Azure Availability Zone ARM Config
  • Google Map API v3 — set bounds and center
  • Convert JavaScript string in dot notation into an…
  • data.table vs dplyr: can one do something well the…
  • Single loss with Multiple output model in TF.Keras
  • Why does C++ code for testing the Collatz conjecture…
  • How to parse JSON with XE2 dbxJSON
  • How to create a link for all mobile devices that…
  • TypeError: Cannot convert a symbolic Keras…
  • For-each over an array in JavaScript
  • How to mark latitude and longitude on Google Maps…
  • Using recursion in a Vue component with JSON
  • How to specify typecllass function type to operate…
  • Convert array to nested JSON object - Angular Material tree
  • Google Maps Android API v2 - Interactive InfoWindow…
  • Logging best practices
  • Argparse will not recognize arguments
  • Get the name of an object's type
  • Multiple markers Google Map API v3 from array of…
  • What is the scope of variables in JavaScript?
  • How to use Servlets and Ajax?
  • What are the undocumented features and limitations…
  • store struct of info in single linked list
  • Wrong response from controller JSP
  • Mismatch Detected for 'RuntimeLibrary'
  • Selenium using Java - The path to the driver…
  • Java: recommended solution for deep cloning/copying…
  • Tensorflow: how to save/restore a model?
  • How do I remove single children in a tree?
  • Extend Underscore.js with `_.mixin()` while keeping…
  • How to interpret this stack frame in my control stack?
  • Event Snippet for Google only shows one event while…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Python selenium get contents of a webpage added by…
  • Calculating score on a quiz test using asp.net C#…
  • python pandas - add unique Ids in column from master…
  • homals package for Nonlinear PCA in R: Error in dimnames(x)
  • How do I observe sub-property changes in Polymer?
  • mongodb group values by multiple fields
  • Adding Input Value Into An Object (Vue.js)
  • Why does the function named "traverse" not work on my code?
  • What is The Rule of Three?
  • Search match multiple values in single field in…
  • Google Map API V3 not working inside polymer-element
  • Google maps Marker Label with multiple characters
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Windows cmd: Parsing output from Ping
  • How do I include a JavaScript file in another…
  • Using CTE in Oracle SQL (ORA-00923: FROM keyword not…
  • Selecting loss and metrics for Tensorflow model
  • What does this symbol mean in JavaScript?
  • Excel JSON VBA Parsing - Determining if an array is empty
  • REGEX help for replacing a value
  • How do I clone a single branch in Git?
  • Avoid creating new session on each axios request laravel
  • Show scroll update when scrolling down page
  • loop and eliminate unwanted lines with beautiful soup
  • geoXML3 "not a LatLngBounds" error in custom…
  • Named tuple and default values for optional keyword…
  • How to traverse the complex nested Json in C# and…
  • Auto-center map with multiple markers in Google Maps API v3
  • Why does git perform fast-forward merges by default?
  • Google Maps how to Show city or an Area outline
  • Error while implementing vue2-google-maps in vue.js…
  • ./components/Avatar.tsx Error: Cannot find module…
  • How to interpret "loss" and "accuracy" for a machine…
  • JavaScript - How to have collision with character…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How can I create a two dimensional array in JavaScript?

Next Post:

How can I reset or revert a file to a specific revision?

Leave a Reply Cancel reply

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

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error