Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Deep/Recursive Copy using $.extend

Tags:

jquery

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

like image 807
LCJ Avatar asked Feb 14 '12 08:02

LCJ


2 Answers

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' }
    
like image 100
Frédéric Hamidi Avatar answered Oct 21 '22 21:10

Frédéric Hamidi


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;
}
like image 33
sinsedrix Avatar answered Oct 21 '22 21:10

sinsedrix