Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deep copy #9

Open
arturdev opened this issue Jun 16, 2014 · 1 comment
Open

Deep copy #9

arturdev opened this issue Jun 16, 2014 · 1 comment

Comments

@arturdev
Copy link

Is there a way do deep copy an object?
Thanks.

@farhankassam2
Copy link

Hi there. I had the same question as you when I was implementing something. There is a way to do this but it is not something directly provided by JavaScript but it worked for me. You can do the following:

let copiedObject = JSON.parse(JSON.stringify(object))

The stringify function first puts the object into a stringified json string and then parses it again, which deep copies the object. However, I warn you that this is an expensive function and can really slow down the program if used many times so use with caution. There are other ways to copy objects I believe and they are as follows:

let copiedObject = Object.assign({}, object) but that does a shallow copy I think. You can refer to its documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Moreover, jQuery provides a way to deep copy too!:

let copiedObject = $.extend(true, {}, objectToBeCopied);
This is a really smart function because it deep copies the object to an empty object, which is the target, and returns the target. Specifying true deep copies the object recursively, which can be significantly faster. You can pass in further objects as arguments to merge those objects into the target empty object. What the function above is doing is that it merges objectToBeCopied into {} and returns the filled {} (the target). Further documentation can be found at https://api.jquery.com/jquery.extend/

Cheers! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants