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

0

3 Answers 3

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

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

5 Comments

you don't have to serialize, I believe [].splice(0,0, arr); will do a copy of primitives
sorry [].concat(arr)
@kirinthos no. Like that you will have the same problem. Check here: jsfiddle.net/jbL0vm9m
uh I said array of primitives
@kirinthos, if you mean array of primitives yes, then you can use just var test3 = test2.slice(); like this: jsfiddle.net/jbL0vm9m/1
0

Objects are essentially references. You must create a new object and assign the values of another object:

var test3 = [ Object.assign({}, test2[0]) ];

Comments

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]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.