641

...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?

1

32 Answers 32

1
2
0

How about using a simple recursive function to get the deep copy of Object/Array

const deepCopyFunction = (inObject) => {
  const deepCopyObject = Array.isArray(inObject) ? [] : {};
  for (const key in inObject) {
    if (typeof inObject[key] === 'object') {
      deepCopyFunction(inObject[key]);
    }
    deepCopyObject[key] = inObject[key];
  }
  return deepCopyObject;
}

Sign up to request clarification or add additional context in comments.

Comments

-1

I think I managed to write a generic method of deep cloning any JavaScript structure mainly using Object.create which is supported in all modern browsers. The code is like this:

function deepClone (item) {
  if (Array.isArray(item)) {
    var newArr = [];

    for (var i = item.length; i-- !== 0;) {
      newArr[i] = deepClone(item[i]);
    }

    return newArr;
  }
  else if (typeof item === 'function') {
    eval('var temp = '+ item.toString());
    return temp;
  }
  else if (typeof item === 'object')
    return Object.create(item);
  else
    return item;
}

1 Comment

Object.create will treat item as the object's prototype, but that is different from cloning. If item is modified, changes will be reflected in its "clone" and vice versa. This approach does not work.
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.