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

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


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 objectconst clone = JSON.parse(JSON.stringify(a));console.log(clone);console.log(typeof clone.date);  // result of .toISOString()