Copying of an array of objects to another Array without object reference in javascript(Deep copy)

Javascript

Javascript Problem Overview


I have a scenario where i need to copy the array of Objects(Main array) to another Temp array which should not have object reference basically if i make any modification to Main array it should not reflect in the Temp array so that i will preserve the copy independently.

I have used one of the code snippet from stack overflow this one does partially like if i delete all objects from the Main array the temp array still hold the value but when i do some modifications in main array and click cancel button iam removing all objects from the main array using array.Removeall(); but the modification still exist in Temp array so which means that object having a reference.

clone: function (existingArray) {
  var newObj = (existingArray instanceof Array) ? [] : {};
  console.debug('newObj value is ' + newObj);
  for (i in existingArray) {
    console.debug('i value is' + i);
    if (i == 'clone') continue;
    console.debug('existingArray[i] value ' + existingArray[i]);
    if (existingArray[i] && typeof existingArray[i] == "object") {

      newObj[i] = this.clone(existingArray[i]);
    } else {
      console.debug('in else part ' + existingArray[i]);
      newObj[i] = existingArray[i];
    }
  }
  return newObj;
}

my object structure is like

iam using knockout framework.

newObjectCreation = function (localIp, RemoteIp, areaId) {
  this.localIP = ko.observable(localIp);
  this.remoteIP = ko.observable(RemoteIp);
  this.areaId = ko.observable(areaId);
};

template.ProtocolArray.push(new newObjectCreation('', '', '')); // to create default row

please help me in this regard. Thanks in advance.

Javascript Solutions


Solution 1 - Javascript

Let me understand: you don't want just have a new array, but you want to create a new instance for all objects are present in the array itself? So if you modify one of the objects in the temp array, that changes is not propagated to the main array?

If it's the case, it depends by the values you're keeping in the main array. If these objects are simple objects, and they can be serialized in JSON, then the quickest way is:

var tempArray = JSON.parse(JSON.stringify(mainArray));

If you have more complex objects (like instances created by some your own constructors, html nodes, etc) then you need an approach ad hoc.

Edit:

If you don't have any methods on your newObjectCreation, you could use JSON, however the constructor won't be the same. Otherwise you have to do the copy manually:

var tempArray = [];
for (var i = 0, item; item = mainArray[i++];) {
    tempArray[i] = new newObjectCreation(item.localIP, item.remoteIP, item.areaId);
}

Solution 2 - Javascript

Lodash can be used for deep copying objects _.cloneDeep(value)

var objects = [{ 'a': 1 }, { 'b': 2 }];

var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// → false

Solution 3 - Javascript

For some other people with the same question. You could also do it this way.
Using the new es6 features you could create a copy of an array (without reference) and a copy of every object without one level of references.

const copy = array.map(object => ({ ...object }))

It's much more functional and idiomatic IMHO

> Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays as the following example shows (it's the same with Object.assign() and spread syntax).
More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

So basically if your objects doesn't have objects as properties. This syntax is everything you need. Unfortunately there is not "out of the box" deep clone feature on the spec but you can always use a library if that's what you need

Browser Compatibility Warning: I think it is part of the specification of Ecma now, but some browsers doesn't have full support of spread syntax jet. But using one of the popular transpilers out there you will be fine

Solution 4 - Javascript

To copy the values of an array without copying the reference of the array, you can simply do:

const tempArray = [...mainArray];

This is the recommended solution for AirBnb's JS Style Guide: https://github.com/airbnb/javascript#arrays

However, this will not create new referenes for the objects inside the array. To create a new reference for the array and the objects inside, you can do:

JSON.parse(JSON.stringify(mainArray));

Solution 5 - Javascript

So you want a deep copy without object reference? Sure, use .slice().

Example:

var mainArr = [],
    tmpArr = []

tmpArr = mainArr.slice(0) // Shallow copy, no reference used.

PS: I don't think double-JSON parsing is performance wise.

Solution 6 - Javascript

You can use Angular's copy: angular.copy();

Solution 7 - Javascript

On nested array you can do:

    const origin = [{ cat: 'Bengal', dog: 'Birman' }, { cat: 'Abyssinian', dog: 'Bombay' }];
    const clone = [];
    origin.forEach(v=> clone.push(Object.assign({}, v)));

Solution 8 - Javascript

Use angular.copy. But not for the whole array (because it would pass array items by reference), but iterate it and use angular.copy on its members.

var newArray = [];
for (var i = 0, item; item = mainArray[i];) {
    newArray[i] = angular.copy(item);
    i++;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsriramdevView Question on Stackoverflow
Solution 1 - JavascriptZER0View Answer on Stackoverflow
Solution 2 - JavascripttomtomssiView Answer on Stackoverflow
Solution 3 - JavascriptIván SánchezView Answer on Stackoverflow
Solution 4 - JavascriptMartin BrandhaugView Answer on Stackoverflow
Solution 5 - JavascriptFlorian MargaineView Answer on Stackoverflow
Solution 6 - JavascriptAlikElzin-kilakaView Answer on Stackoverflow
Solution 7 - Javascriptdawid debinskiView Answer on Stackoverflow
Solution 8 - Javascriptmichal.jakubeczyView Answer on Stackoverflow