DEV Community

Discussion on: JavaScript Interviews: Create a deep copy of an object

Collapse
 
garystorey profile image
Gary Storey • Edited

You can also use
JSON.parse(JSON.stringify(obj))

Collapse
 
jankapunkt profile image
Jan Küster

But stringify removes lots of things so you need to write reviver etc. to support instances or constructor refrrences

Collapse
 
garystorey profile image
Gary Storey

This example, and the problem statement, are using a nested data structure; not functions or constructors. For the purposes outlined above this is perfectly valid.

Collapse
 
thesanjeevsharma profile image
Sanjeev Sharma

Haha! Gary 1 Interviewer 0 😂

Collapse
 
sgoulas profile image
sgoulas

This is indeed a nice trick, but do keep in mind that in order for this to work the object must not contain dates, functions, undefined, infinity, nan, regexes, maps, sets, blobs, file lists, image data, sparce / typed arrays or any other complex types. For the majority of the cases though it will do the trick.

Collapse
 
garystorey profile image
Gary Storey

If there had been any of the above mentioned, then I would not have recommended my approach.

As you stated this works in the majority of situations and for the examples given.