Reputation: 19641
How to deep copy an object in javascript as object not as array
var x = {attr1: "value", attr2: "value"};
var y = $.extend(true, [], x);
var z = $.extend(true, [], x);
alert($.type(x)); // object
alert($.type(y)); // array [ why not object too ]
alert($.type(z)); // array [ why not object too ]
Upvotes: 2
Views: 298
Reputation: 1
To make a deep copy of an object in javascript is to do JSON.parse(JSON.stringify(obj)). In the context of your question, this could be done as follows:
var x = {attr1: "value", attr2: "value"};
var deep_copy = JSON.parse(JSON.stringify(x));
Upvotes: 0
Reputation: 55740
Instead of
var y = $.extend(true, [], x);
Try
var y = $.extend(true, {}, x);
^^--------- Empty object instead of empty Array
Upvotes: 5