0
One of the most frequently requested features by new Javascript developers is how to duplicate an object. It seems as if there should be a native method copy()
, right? Turns out it’s a little more complicated than that, because it’s not entirely clear by default, what the duplication algorithm should be?
What type of object? It can be represented in a JSON?
– Sergio
Yes can be represented on a JSON.
– Cristiano Gilberto João
Is not enough
const copy = JSON.parse(JSON.stringify(obj));
?– Sergio
Note that not always an object will be JSON-safe. JSON-safe which can be serialized to a JSON string and then re-transformed into an object with the same structure and values
– Cristiano Gilberto João
If you actually have functions associated with them they get lost in this example with
JSON.parse
andJSON.stringify
, but this was something you did not clarify in the question. Regardless of this the question marked as duplicate has answers even for this case.– Isac
Sergio and Isac Thanks for the feedback. In fact the other question already has answers you were looking for.
– Cristiano Gilberto João