How to clone a javascript object? By copying and not by reference?

Asked

Viewed 1,338 times

3

I need to copy a javascript object to be able to manipulate the copy freely. But when I try to copy the object normally through the sign =, the "copy" is performed by reference. That is, I actually wish the object to be "cloned".

See the Jsfiddle with the example:

1 answer

1

If your object has no sub-objects then you only need a "shallow" clone. If the object has sub-objects that you also want to manipulate, then you need a "background clone".

I would recommend using a library such as Undercore.js or Lo-Dash which have utilitarian methods for both forms of cloning.

If your object only contains data of primitive types (Boolean, Number, String, Null) or other sub-objects or arrays of sub-objects also only with primitive types, ie, your object is quite simple, no dates or custom Objects, so there is a kind of inelegant shortcut but it works: var clone = JSON.parse(JSON.stringify(seuObjeto));.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.