Pho Huynh
Pho Huynh

Reputation: 1577

Deep copy an array with Array.prototype.slice()

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.

Upvotes: 3

Views: 2314

Answers (1)

Igor
Igor

Reputation: 62318

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

Upvotes: 4

Related Questions