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
3 Answers
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"}
5 Comments
kirinthos
you don't have to serialize, I believe
[].splice(0,0, arr); will do a copy of primitiveskirinthos
sorry
[].concat(arr)Sergio
@kirinthos no. Like that you will have the same problem. Check here: jsfiddle.net/jbL0vm9m
kirinthos
uh I said array of primitives
Sergio
@kirinthos, if you mean array of primitives yes, then you can use just
var test3 = test2.slice(); like this: jsfiddle.net/jbL0vm9m/1Use 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]);