I am trying to merge two objects using jQuery $.extend.
Using the following code, I am trying to alert ( “Ball – Stump - Umpire”). But the current output is ( “Undefined – Stump - Umpire”). It does not achieve the deep (recursive) copy. How do we correct this?
$(document).ready(function () {
debugger;
//$.extend
var obj3 = { throwable: { text1: 'Ball' }, text3: 'Umpire' };
var obj4 = { throwable: { text4: 'Bat' }, text2: 'Stump' }
//Simple Copy
var result1 = $.extend(obj3, obj4);
//alert(result1.throwable.text4 + " - " + result1.text2 + " - " + result1.text3);
//Deep Copy
//First parameter is passed as Boolean true to accomplish deep (recursive) copy
var result2 = $.extend(true, obj3, obj4);
alert(result2.throwable.text1 + " - " + result2.text2 + " - " + result2.text3);
});
EDIT: I referred
(Deep) copying an array using jQuery
Your second code snippet does work as expected and performs a deep copy of obj4
into obj3
, when run in isolation.
The problem is, the previous code snippet has already performed a shallow copy of obj4
into obj3
, completely overriding its throwable
member with obj4
's in the process. Therefore, throwable.text1
does not exist anymore within obj3
after that code has run.
Initially, obj3
is :
{ throwable: { text1: 'Ball' }, text3: 'Umpire' }
After the first code snippet has run, obj3
becomes :
{ throwable: { text4: 'Bat' }, text3: 'Umpire', text2: 'Slump' }
Finally, after the second code snippet has run, obj3
still is:
{ throwable: { text4: 'Bat' }, text3: 'Umpire', text2: 'Slump' }
In your code, text1
property is overwritten by extend
. I f you want a method that contacenates strings, code your own, extend
don't do that.
Something like:
function(o1, o2) {
var ores = {};
for(var p in o1) ores.p = o1.p;
for(var p in o2) ores.p = ores.p ? ores.p+o2.p : o2.p;
return ores;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With