2

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 ]
1

2 Answers 2

5

Instead of

var y = $.extend(true, [], x);

Try

var y = $.extend(true, {}, x);
                       ^^--------- Empty object instead of empty Array
Sign up to request clarification or add additional context in comments.

1 Comment

I've tried several different ways of doing this, but this one works the best for object 'arrays'
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.