Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  115] [ 1]  / answers: 1 / hits: 17557  / 14 Years ago, fri, august 13, 2010, 12:00:00

Possible Duplicate:

What is the most efficient way to clone a JavaScript object?






How to clone js object with out reference like these:



{ ID: _docEl,
Index: next,
DocName: _el
}


Any ideas?


More From » javascript

 Answers
16

Edit: New visitors should probably head to this question. There is a new (as of this writing) browser supported function called structuredClone() that will be useful as browsers and engines adopt it.


Still consider the additional considerations I write below:




You'll have to iterate over the object and make copies of all its properties.


And then if any of its properties are also objects, assuming you want to clone those too, you'll have to recurse into them.


There's various methods for doing this here:
What is the most efficient way to clone a JavaScript object?


Doing this isn't a perfect copy - depending on how it's done the new object won't inherit the original object's relationship to its prototype and you won't be able to maintain the same distinction between copied properties that were from the prototypal chain or from the object itself. And built-in objects (like DOM nodes) won't copy properly. In the case of DOM nodes you can clone those with their own cloneNode().


Additional considerations


Consider whether your application really needs to clone the object or whether some other design might be appropriate.


Cloning an object by copying all its properties will create two separate copies of all its properties, and if you modify one's properties the other object won't change. If you don't need this to be the case, simply copying the object will suffice.


You can also consider using prototypes (or the newer class syntax) and new which effectively creates objects with a set of properties from a prototype that can be overridden naturally or have fall-back to those in the prototype.


Or, finally, if you wanted to add properties or methods to the new object without affecting the original object, can you just encapsulate object A into object B, that is, have object A as a property in object B, so that you can still get the reference to the original object as b.a.property, but can add properties to b alone as b.property.


[#95927] Wednesday, August 11, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
braidenv

Total Points: 80
Total Questions: 104
Total Answers: 91

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
;