How do you clone an array of objects in JavaScript?

…where each object also has references to other objects within the same array?

When I first came up with this problem I just thought of something like

var clonedNodesArray = nodesArray.clone()

would exist and searched for information on how to clone objects in JavaScript. I did find a question on Stack Overflow (answered by the very same @JohnResig) and he pointed out that with jQuery you could do

var clonedNodesArray = jQuery.extend({}, nodesArray);

to clone an object. I tried this though, and this only copies the references of the objects in the array. So if I

nodesArray[0].value = "red"
clonedNodesArray[0].value = "green"

the value of both nodesArray[0] and clonedNodesArray[0] will turn out to be “green”. Then I tried

var clonedNodesArray = jQuery.extend(true, {}, nodesArray);

which deep copies an Object, but I got “too much recursion” and “control stack overflow” messages from both Firebug and Opera Dragonfly respectively.

How would you do it? Is this something that shouldn’t even be done? Is there a reusable way of doing this in JavaScript?

36 s
36

Leave a Comment