How to duplicate Objects in Javascript

Asked

Viewed 19 times

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?

  • Yes can be represented on a JSON.

  • Is not enough const copy = JSON.parse(JSON.stringify(obj));?

  • 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

  • 1

    If you actually have functions associated with them they get lost in this example with JSON.parse and JSON.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.

  • Sergio and Isac Thanks for the feedback. In fact the other question already has answers you were looking for.

Show 1 more comment
No answers

Browser other questions tagged

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