In a project I'm working on, I need to clone an object to a variable.
I first tried - what seemed to be the most obvious solution - to do var obj2 = obj1
, however I soon realized this makes obj2
refer to obj1
, so whenever I set a property in obj2
, the property is updated in obj1
, too. Well, I can't have that.
So, I started searching around for ways to clone a object in JavaScript - I found multiple solutions for this, mainly var obj2 = JSON.parse(JSON.stringify(obj1))
- but that didn't keep all getters and setters I had defined for my object!
The now most obvious solution to me seems to firstly use the JSON trick above to make obj2
have all of obj1
's properties, then loop through all of the objects getters and setters and add them back using Object.defineProperty()
, but I have yet to find a way to get all getters/setters of an object.