roomorama / RMMapper

Other
208 stars 42 forks source link

Deep copy #9

Open arturdev opened 10 years ago

arturdev commented 10 years ago

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

farhankassam2 commented 6 years ago

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! 👍