3

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

Dani
  • 3,128
  • 2
  • 43
  • 91

3 Answers3

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