I'm trying to assign an array of objects to another array but when I created the new array and in others functions I change its value, the original array changes as well (which is not ok). Could I use another way? This is an example: http ://codepen.io/Xiwi/pen/rLMbYp
            Asked
            
        
        
            Active
            
        
            Viewed 135 times
        
    3 Answers
3
            Looks like you need to copy/clone the array so it will not be changed by reference.
If you have only Primitive Types in the array you can do like this:
var test3 = JSON.parse(JSON.stringify(test2));
otherwise you need a recursive solution and to be more specific in your question.
Example:
var test1 = [{name: 'test1'}];
var test2 = [{name: 'test2'}];
var test3 = JSON.parse(JSON.stringify(test2));
test3[0].name = 'test3';
// Open console
console.log('Test2: ',test2[0]); // Object {name: "test2"}
console.log('Test3: ',test3[0]); // Object {name: "test3"}
        Sergio
        
- 28,539
 - 11
 - 85
 - 132
 
- 
                    you don't have to serialize, I believe `[].splice(0,0, arr);` will do a copy of primitives – kirinthos Jun 21 '16 at 00:10
 - 
                    sorry `[].concat(arr)` – kirinthos Jun 21 '16 at 00:25
 - 
                    @kirinthos no. Like that you will have the same problem. Check here: https://jsfiddle.net/jbL0vm9m/ – Sergio Jun 21 '16 at 08:43
 - 
                    uh I said array of primitives – kirinthos Jun 21 '16 at 10:07
 - 
                    @kirinthos, if you mean array of primitives yes, then you can use just `var test3 = test2.slice();` like this: https://jsfiddle.net/jbL0vm9m/1/ – Sergio Jun 21 '16 at 10:12
 
0
            
            
        Objects are essentially references. You must create a new object and assign the values of another object:
var test3 = [ Object.assign({}, test2[0]) ];
        BotNet
        
- 2,759
 - 2
 - 16
 - 17
 
0
            
            
        Use simple .map to copy one array of objects to another.
var test1 = [{name: 'test1'}];
var test2 = [{name: 'test2'}];
//var test3 = test2.slice(0); //doesn't work. objects are still references
var test3 = test2.map(function(obj){
  //return obj; //doesn't work. objects are still references
  var o={}; //create brand new object
  for(var prop in obj)
    o[prop]=obj[prop];//assign properties
  return  o;//works
});
test3[0].name = 'test3';
// Open console
console.log('Test2: ',test2[0]);
console.log('Test3: ',test3[0]);
        Alex Kudryashev
        
- 9,120
 - 3
 - 27
 - 36