Reputation: 33
I am trying to copy an array to a new variable and then modify the array.
Code:
var test = [
{ test: "test1", arr: ["1", "2", "3"] },
{ test: "test2", arr: ["4", "5", "6"] }
];
console.log("test before", test);
console.log("test before", test[1]);
console.log("test before", test[1].arr);
var t2 = [...test] // used .slice(0) but same result
t2[1].arr = t2[1].arr.slice(0, 1);
console.log("test after", test[1].arr);
console.log("t2", t2[1].arr);
output:
test before:
0: {test: "test1", arr: Array(3)} //arr: (3) ["1", "2", "3"]
1: {test: "test2", arr: Array(1)} // arr: (1) ["4"]
test before:
{test: "test2", arr: Array(3)} //arr: (1) "4"
test before: (3) ["4", "5", "6"]
test after: ["4"]
t2: ["4"]
As you can see spread operator/ slice() is modifying the original value.
I also tried to use var t2 = Object.Create(test)
[same result].
Upvotes: 0
Views: 3780
Reputation: 36574
When you assign a an Object/Array to a variable it doesnot copy it. I just sets a reference to original Object/Array. You should use Object.assign
for shallow cloning and JSON.parse(JSON.stringify(obj))
for deep cloning
Note: arrays are actually objects in javascript
var test = [
{ test: "test1", arr: ["1", "2", "3"] },
{ test: "test2", arr: ["4", "5", "6"] }
];
console.log("test before", test);
console.log("test before", test[1]);
console.log("test before", test[1].arr);
var t2 = JSON.parse(JSON.stringify(test)) // used .slice(0) but same result
t2[1].arr = t2[1].arr.slice(0, 1);
console.log("test after", test[1].arr);
console.log("t2", t2[1].arr);
JSON.parse(JOSN.stringify(obj))
is not much efficient and will give wrong output in some cases.
$.extend(true, {}, obj);
_.cloneDeep(value)
here You can find detail about this
Upvotes: 1
Reputation: 387
Array spread (or Array.slice()) are only shallow copy of original array, so sub object are still the same.
For more details about deep copy of objects, take a look at: How do you clone an Array of Objects in Javascript?
Upvotes: 0