If your object is "small" and contains exclusively serializable properties, a simple deepCopy hack using JSON serialization should be OK. But, if your object is large, you could run into problems. And if it contains unserializable properties, those'll go missing:

var o = {
 a: 1,
 b: 2,
 sum: function() { return a + b; }
};

var o2 = JSON.parse(JSON.stringify(o));
console.log(o2);

Yields:

Object {a: 1, b: 2}

Interestingly enough, a fair number of deep-copy solutions in C# are similar serialization/deserialization tricks.

Addendum: Not sure what you're hoping for in terms of comparing the objects after the copy. But, for complex objects, you generally need to write your own Compare() and/or Equals() method for an accurate comparison.

Also notable, this sort of copy doesn't preserve type information.

JSON.parse(JSON.stringify(new A())) instanceof A === false
Answer from svidgen on Stack Overflow
🌐
Amit Merchant
amitmerchant.com › deep-copy-objects-using-json-stringify-json-parse
Deep copying objects using JSON.stringify and JSON.parse
January 13, 2021 - This will essentially perform deep copying of the object. So, our previous example would look like so. let user1 = { name: 'Amit', age: 30, school: { name: 'SCET' } }; let user2 = JSON.parse(JSON.stringify(user1)); user2.name = 'Jemini'; user2.school.name = 'Kadiwala' console.log(user2); // { name: 'Jemini', age: 30, school: { name: 'Kadiwala' } } console.log(user1); // { name: 'Amit', age: 30, school: { name: 'SCET' } }
Discussions

Javascript deep copy using JSON.parse and JSON.stringify - Stack Overflow
Is the below method a foolproof way of deep copying an object in Javascript i.e. even for very deeply nested objects/arrays ? ... No. It doesn't work for circular objects and everything that contains non-plain objects or arrays. And it might not work for really large objects. ... But there is a solution how do it if circular exist. The question is understated in the status it makes no sense to answer ... As metioned in other answer JSON ... More on stackoverflow.com
🌐 stackoverflow.com
January 11, 2021
What is the most efficient way to deep clone an object in JavaScript? - Stack Overflow
If you do not use Dates, functions, ... liner to deep clone an object is: ... Copyconst 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.stri... More on stackoverflow.com
🌐 stackoverflow.com
What are the dangers of Deep-copying objects using JSON.parse(JSON.stringify(obj))?
I would recommend checking out ... deep copying. ... Any internal getters and setters will be lost. Destruction of date objects (Dates will be converted to strings · Class prototypes will be lost. The JSON method will also throw an exception when parsing circular ... More on stackoverflow.com
🌐 stackoverflow.com
[Performance] Deep Copy vs JSON Stringify / JSON Parse
I've noticed a lot of places in the code that makes copy of an object by using JSON Stringify + JSON Parse. I have found a jsPerf that compares few technics for deep object cloning and this one is ... More on github.com
🌐 github.com
3
February 28, 2018
🌐
Medium
medium.com › @pmzubar › why-json-parse-json-stringify-is-a-bad-practice-to-clone-an-object-in-javascript-b28ac5e36521
Why use JSON “parse” and “stringify” methods a bad practice to clone objects in JavaScript (2023 update) | by Petro Zubar | Medium
October 10, 2023 - By the way, I found such a ‘deep cloning’ in my own old code! The JSON.stringify() just converts a JavaScript value to a JSON string. It`s ok to use it with some primitives like Numbers, Strings or Booleans.
🌐
Built In
builtin.com › software-engineering-perspectives › json-stringify
How to Use JSON.stringify() and JSON.parse() in JavaScript | Built In
As a note, JSON.parse(JSON.stringify()) performs a shallow deep copy (i.e., it copies structure, not full fidelity across all types).
🌐
DEV Community
dev.to › rajusaha › stop-using-jsonparsejsonstringifyobject-for-deep-cloning-try-this-instead-2cmc
Stop Using JSON.parse(JSON.stringify(object)) for Deep Cloning! Try This Instead - DEV Community
June 24, 2024 - To address the above issue, we can use the structuredClone() global function for a deep copy. The structuredClone() method is supported by modern browsers and can handle transferable objects efficiently.
🌐
GitHub
gist.github.com › djD-REK › 89d1f8d51050f7977d21b629b137140b
JSON.parse() followed by JSON.stringify() as a deep copy.js · GitHub
Share Copy sharable link for this gist. Clone via HTTPS Clone using the web URL. Learn more about clone URLs · Clone this repository at <script src="https://gist.github.com/djD-REK/89d1f8d51050f7977d21b629b137140b.js"></script> Save djD-REK/89d1f8d51050f7977d21b629b137140b to your computer and use it in GitHub Desktop. Download ZIP · Raw · JSON.parse() followed by JSON.stringify() as a deep copy.js ·
Find elsewhere
Top answer
1 of 16
6003

Native deep cloning

There's now a structuredClone(value) function supported in all major browsers and node >= 17. It has polyfills for older systems.

structuredClone(value)

If needed, loading the polyfill first:

import structuredClone from '@ungap/structured-clone';

See this answer for more details, but note these limitations:

  • Function objects cannot be duplicated by the structured clone algorithm; attempting to throws a DataCloneError exception.
  • Cloning DOM nodes likewise throws a DataCloneError exception.
  • Certain object properties are not preserved:
    • The lastIndex property of RegExp objects is not preserved.
    • Property descriptors, setters, getters, and similar metadata-like features are not duplicated. For example, if an object is marked readonly with a property descriptor, it will be read/write in the duplicate, since that's the default.
    • The prototype chain is not walked or duplicated.

Older answers

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()
Run code snippetEdit code snippet Hide Results Copy to answer Expand

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
  • Ramda - clone
  • AngularJS - angular.copy
  • jQuery - jQuery.extend(true, { }, oldObject); .clone() only clones DOM elements
  • just library - just-clone; Part of a library of zero-dependency npm modules that do just do one thing. Guilt-free utilities for every occasion.
2 of 16
2501

Checkout this benchmark: http://jsben.ch/#/bWfk9

In my previous tests where speed was a main concern I found

JSON.parse(JSON.stringify(obj))

to be the slowest way to deep clone an object (it is slower than jQuery.extend with deep flag set true by 10-20%).

jQuery.extend is pretty fast when the deep flag is set to false (shallow clone). It is a good option, because it includes some extra logic for type validation and doesn't copy over undefined properties, etc., but this will also slow you down a little.

If you know the structure of the objects you are trying to clone or can avoid deep nested arrays you can write a simple for (var i in obj) loop to clone your object while checking hasOwnProperty and it will be much much faster than jQuery.

Lastly if you are attempting to clone a known object structure in a hot loop you can get MUCH MUCH MORE PERFORMANCE by simply in-lining the clone procedure and manually constructing the object.

JavaScript trace engines suck at optimizing for..in loops and checking hasOwnProperty will slow you down as well. Manual clone when speed is an absolute must.

var clonedObject = {
  knownProp: obj.knownProp,
  ..
}

Beware using the JSON.parse(JSON.stringify(obj)) method on Date objects - JSON.stringify(new Date()) returns a string representation of the date in ISO format, which JSON.parse() doesn't convert back to a Date object. See this answer for more details.

Additionally, please note that, in Chrome 65 at least, native cloning is not the way to go. According to JSPerf, performing native cloning by creating a new function is nearly 800x slower than using JSON.stringify which is incredibly fast all the way across the board.

Update for ES6

If you are using Javascript ES6 try this native method for cloning or shallow copy.

Object.assign({}, obj);
🌐
DEV Community
dev.to › ml318097 › deep-cloning-json-parse-json-stringify-5708
Deep Cloning (JSON.parse + JSON.stringify) - DEV Community
February 20, 2021 - const obj = { name: "Joe", address: ... arrays & objects reference is copied instead of their values) whereas, stringify + parse does a deep copy....
🌐
JavaScript in Plain English
javascript.plainenglish.io › dont-deep-copy-with-json-stringify-and-json-parse-in-js-here-s-why-c3f2783661e9
Don’t Deep Copy With JSON.Stringify and JSON.Parse in JS — Here’s Why
January 6, 2023 - Don’t Deep Copy With JSON.Stringify and JSON.Parse in JS — Here’s Why If you care about common data types include Date objects and undefined getting deep copied correctly, watch out for this …
🌐
Melvin George
melvingeorge.me › blog › deep-clone-copy-array-of-objects-using-json-stringify-javascript
How to deep clone or copy an array of objects using the JSON.stringify() method in JavaScript? | MELVIN GEORGE
July 14, 2021 - // array of objects const objsArr = [{ name: "John Doe" }, { name: "Roy Daniel" }]; // first convert the array into a string // using the JSON.stringify() method const objsArrStr = JSON.stringify(objsArr); // conver the string again to array of objects // using the JSON.parse() method const objsArrDeepCopy = JSON.parse(objsArrStr); console.log(objsArrDeepCopy); // copied array of objects -> [{ name: "John Doe" }, { name: "Roy Daniel" }] We successfully made a deep copy of the array with all the object elements inside having a new reference to it.
🌐
Educative
educative.io › answers › how-to-deep-copy-in-javascript
How to deep copy in JavaScript
The deepClone method in lodash can be used to easily deep clone an object. import _ from 'lodash'; var original = [{ 'a': 1 }, { 'b': 2 }]; var copy = _.cloneDeep(original); console.log(copy) console.log(copy[0] === original[0]); // false as different objects now · Run · If your object is not too complex, you can use the JSON.parse and JSON.stringify methods to make a deep copy.
🌐
GitHub
gist.github.com › sstur › 7576927
Deep-copy an object, similar to calling JSON.parse(JSON.stringify(obj)) but preserves dates and undefined · GitHub
November 21, 2013 - Deep-copy an object, similar to calling JSON.parse(JSON.stringify(obj)) but preserves dates and undefined - clone.js
🌐
Medium
dinesh-rawat.medium.com › why-you-should-avoid-json-parse-json-stringify-for-cloning-objects-in-javascript-8337d6761926
Why you should avoid JSON.parse(JSON.stringify()) for cloning objects in JavaScript | by Dinesh Rawat | Medium
March 29, 2023 - These libraries provide functions that create a deep copy of an object or array, including any nested objects or arrays. ... It’s important to choose the appropriate cloning method based on the complexity of the object you want to clone, as ...
🌐
javaspring
javaspring.net › blog › javascript-deep-copy-using-json
JavaScript Deep Copy Using JSON Stringify and Parse: Does It Work? A Practical Guide — javaspring.net
The JSON.stringify() method converts a JavaScript object or value into a JSON string. JSON.parse() then parses that string back into a new JavaScript object. Together, they看似 create a deep copy by serializing and deserializing the data:
🌐
DEV Community
dev.to › jahid6597 › comment › 2g40c
JSON.parse(JSON.stringify(object)) efficiently creates a copy of simple objec... - DEV Community
June 24, 2024 - JSON.parse(JSON.stringify(object)) efficiently creates a copy of simple objects by converting them to a JSON string and back, but loses complex data types like NaN, Set and Map.
🌐
Jsperf
jsperf.com › deep-copy-vs-json-stringify-json-parse
Deep Copy vs JSON Stringify / JSON Parse · jsPerf
[] : {}; for (k in o) { copy[k] = deepCopy(o[k]); } } return copy; } var uc = {bir:{iki:{uc:3}}} }; </script>
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › stringify
JSON.stringify() - JavaScript - MDN Web Docs
If you are using JSON.stringify() to deep-copy an object, you may instead want to use structuredClone(), which supports circular references.
🌐
GitHub
github.com › raml-org › raml-js-parser-2 › issues › 814
[Performance] Deep Copy vs JSON Stringify / JSON Parse · Issue #814 · raml-org/raml-js-parser-2
February 28, 2018 - I've noticed a lot of places in the code that makes copy of an object by using JSON Stringify + JSON Parse. I have found a jsPerf that compares few technics for deep object cloning and this one is the slowest one: https://jsperf.com/deep-copy-vs-json-stringify-json-parse/5
Author   raml-org