How to clone a javascript object? By copy and not by reference? [duplicate]

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 done by reference. That is, I actually want the object to be "cloned."

See JsFiddle with the example:

    
asked by anonymous 19.09.2014 / 22:02

1 answer

1

If your object does not have 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 like Undercore.js or Lo-Dash that 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 sub-object arrays also only with primitive types, ie your object is very simple, with no dates or custom objects, so there is a shortcut that is somewhat inelegant but that works: var clone = JSON.parse(JSON.stringify(seuObjeto)); .

    
19.09.2014 / 22:53