Reputation: 20916
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')
})
I dont see the second debug stmt printed in the console.log
Upvotes: 1
Views: 46
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