3

I have known that we can use Array.prototype.slice() to perform a deep copy on array.

var a = [1,2];
var b = a.slice();
b.push(3);
console.log(a);

result:

[1,2]

But in my case, I used it to perform deep copy on an array of objects. And the result was not something I would expect.

var a = [{},{"chosen": true}];
var b = a.slice();
b[0]["propa"] = 1;
console.log(a);

result:

[{"propa":1},{"chosen":true}]

Someone shows me how to work around in this situation. Thanks.

Pho Huynh
  • 1,497
  • 3
  • 13
  • 23
  • 1
    Related: [What is the most efficient way to clone an object?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object) and [How do I correctly clone a JavaScript object?](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – Jonathan Lonowski Jul 13 '16 at 19:12

1 Answers1

4

You can use the JSON object to serialize and deserialize the array.

var a = [{},{"chosen": true}];
var b = JSON.parse(JSON.stringify(a));
b[0]["propa"] = 1;
console.log(a);
Igor
  • 60,821
  • 10
  • 100
  • 175
  • 3
    This only works as long as the contained objects don't have dates, functions or other values that are impermissible in JSON – Dexygen Jul 13 '16 at 19:19
  • @GeorgeJempty - you are 100% right. I did upvote the comment by Jonathan as this question has been answered before. Maybe better to mark it as a duplicate. – Igor Jul 13 '16 at 19:21
  • I don't know if there are any other solutions but this works perfectly for me. Thank you. – Pho Huynh Jul 13 '16 at 19:22
  • @GeorgeJempty: yeah, I see. – Pho Huynh Jul 13 '16 at 19:23