25

Copying an array of objects into another array in javascript using slice(0) and concat() doesnt work.

I have tried the following to test if i get the expected behaviour of deep copy using this. But the original array is also getting modified after i make changes in the copied array.

var tags = [];
for(var i=0; i<3; i++) {
    tags.push({
        sortOrder: i,
        type: 'miss'
    })
}
for(var tag in tags) { 
    if(tags[tag].sortOrder == 1) {
        tags[tag].type = 'done'
    }
}
console.dir(tags)

var copy = tags.slice(0)
console.dir(copy)

copy[0].type = 'test'
console.dir(tags)

var another = tags.concat()
another[0].type = 'miss'
console.dir(tags)

How can i do a deep copy of a array into another, so that the original array is not modified if i make a change in copy array.

jsbisht
  • 9,079
  • 7
  • 50
  • 55
  • I'm not sure what you're trying to do but. I suggest changing your second for loop to a `for of` loop `for of(var tag of tags) { if(tag.sortOrder == 1) { tag.type == 'done' }}` – Edwin Reynoso Feb 12 '15 at 19:55
  • Depending on your environment, you might try Object.create? – Zlatko Feb 12 '15 at 23:17
  • @zlatko can you give an example of the same – jsbisht Feb 13 '15 at 04:00
  • Oh, var newObject = Object.create(oldObject) should give you a __proto__ based and dereferenced clone of the old object. Not sure about arrays, buy you can try. The environment part of the comment is that I don't know if you're on V8 or maybe other JS engines, I think it's not supported everywhere (but there are polyfils). – Zlatko Feb 13 '15 at 08:50
  • Actually it seems it is: http://kangax.github.io/compat-table/es5/#Object.create – Zlatko Feb 13 '15 at 08:52

10 Answers10

77

Try

var copy = JSON.parse(JSON.stringify(tags));
dangh
  • 796
  • 4
  • 4
  • Over a yeah and a half old, and still helpful ! – Kesem David Sep 13 '16 at 21:55
  • 7
    @Aerious Well, this works because you're serializing the array/object into a string. When you parse that string, entirely new objects are instantiated, as if you received a payload from some api. References are not preserved though, so if you have array elements that point to other elements, this will be dangerous. – Sava B. Apr 13 '17 at 15:23
  • @SavaB. Agreed :) – Aerious Apr 14 '17 at 06:25
  • 1
    Keep in mind that it won't work if any of objects (tags) in the array is a circular structure, meaning that it references itself indirectly. That case will end up with "TypeError: Converting circular structure to JSON" error. – Wojtek Majerski Aug 25 '17 at 13:29
14

Try the following

// Deep copy
var newArray = jQuery.extend(true, [], oldArray);

For more details check this question out What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
Marko
  • 2,734
  • 24
  • 24
5

As mentioned Here .slice(0) will be effective in cloning the array with primitive type elements. However in your example tags array contains anonymous objects. Hence any changes to these objects in cloned array are reflected in tags array.

@dangh's reply above derefences these element objects and create new ones.

Here is another thread addressing similar situation

Community
  • 1
  • 1
bp4D
  • 915
  • 12
  • 20
4

A nice way to clone an array of objects with ES6 is to use spread syntax:

const clonedArray = [...oldArray];

MDN

Binaromong
  • 540
  • 7
  • 26
1

Easiest and the optimistic way of doing this in one single line is using Underscore/Lodash

let a = _.map(b, _.clone)

1

You just need to use the '...' notation.

// THE FOLLOWING LINE COPIES all elements of 'tags' INTO 'copy'
var copy = [...tags]

When you have an array say x, [...x] creates a new array with all the values of x. Be careful because this notation works slightly differently on objects. It splits the objects into all of its key, value pairs. So if you want to pass all the key value pairs of an object into a function you just need to pass function({...obj})

Anant Sinha
  • 159
  • 1
  • 10
0

Same issue happen to me. I have data from service and save to another variable. When ever I update my array the copied array also updated. old code is like below

//$scope.MyData get from service
$scope.MyDataOriginal = $scope.MyData;

So when ever I change $scope.MyData also change $scope.MyDataOriginal. I found a solution that angular.copy right code as below

$scope.MyDataOriginal = angular.copy($scope.MyData);
0

I know that this is a bit older post but I had the good fortune to have found a decent way to deep copy arrays, even those containing arrays, and objects, and even objects containing arrays are copied... I only can see one issue with this code is if you don't have enough memory I can see this choking on very large arrays of arrays and objects... But for the most part it should work. The reason that I am posting this here is that it accomplishes the OP request to copy array of objects by value and not by reference... so now with the code (the checks are from SO, the main copy function I wrote myself, not that some one else probably hasn't written before, I am just not aware of them)::

var isArray = function(a){return (!!a) && (a.constructor===Array);}
var isObject = function(a){return (!!a) && (a.constructor===Object);}
Array.prototype.copy = function(){
    var newvals=[],
        self=this;
    for(var i = 0;i < self.length;i++){
        var e=self[i];
        if(isObject(e)){
            var tmp={},
                oKeys=Object.keys(e);
            for(var x = 0;x < oKeys.length;x++){
                var oks=oKeys[x];
                if(isArray(e[oks])){
                    tmp[oks]=e[oks].copy();
                } else { 
                    tmp[oks]=e[oks];
                }
            }
            newvals.push(tmp);
        } else {
            if(isArray(e)){
                newvals.push(e.copy());
            } else {
                newvals.push(e);
            }
        }
    }
    return newvals;
}

This function (Array.prototype.copy) uses recursion to recall it self when an object or array is called returning the values as needed. The process is decently speedy, and does exactly what you would want it to do, it does a deep copy of an array, by value... Tested in chrome, and IE11 and it works in these two browsers.

Jesse Fender
  • 321
  • 2
  • 14
0

The way to deeply copy an array in JavaScript with JSON.parse:

let orginalArray=
[
 {firstName:"Choton", lastName:"Mohammad", age:26},
 {firstName:"Mohammad", lastName:"Ishaque", age:26}
];

let copyArray = JSON.parse(JSON.stringify(orginalArray));
copyArray[0].age=27;

console.log("copyArray",copyArray);
console.log("orginalArray",orginalArray);
-1

For this i use the new ECMAScript 6 Object.assign method :

let oldObject = [1,3,5,"test"];
let newObject = Object.assign({}, oldObject)

the first argument of this method is the array to be updated, we pass an empty object because we want to have a completely new object,

also you can add other objects to be copied too :

let newObject = Object.assign({}, oldObject, o2, o3, ...)
Chtioui Malek
  • 11,197
  • 1
  • 72
  • 69
  • 1
    even with Object.assign you have same issues, every method that exists right now in Javascript works ok with primitives, if you have your object with keys that have as value another object, references will be kept – pauldcomanici Sep 06 '17 at 09:21