user1050619
user1050619

Reputation: 20916

Copying a Javascript object

Im trying to do a deep copy of a Javascript object using Jquery.extend but I don't it being copied...

Here is a simple example:

$(document).ready(function(){
        console.log('Hi')
        var obj1 = [{'name':'bob','age':'20'},{'name':'Tom','age':'20'}];
        jQuery.extend(obj2,obj1)
        console.log('Hi')

})

JSFiddle

I dont see the second debug stmt printed in the console.log

Upvotes: 1

Views: 46

Answers (1)

James M
James M

Reputation: 16728

You need to declare obj2 first:

    console.log('Hi')
    var obj1 = [{'name':'bob','age':'20'},{'name':'Tom','age':'20'}];
    var obj2 = {}
    jQuery.extend(obj2,obj1)
    console.log('Hi')

The new array will still be working with the same objects, however. If you want a deep copy (that is, an array with a new copy of the objects inside it), pass true for the deep parameter of jQuery.extend:

    jQuery.extend(true, obj2,obj1)

Upvotes: 3

Related Questions