LCJ
LCJ

Reputation: 22662

jQuery Deep/Recursive Copy using $.extend

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

Upvotes: 13

Views: 7210

Answers (3)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262979

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' }
    

Upvotes: 8

Alex
Alex

Reputation: 2126

The problem is, that there are two properties with the same name in the objects: text1. Even with deep extends, jquery extend doesn't merge this into a new concat string or an array.

Deep copy is relevant, if one of your properties is another object. With deep extend, all properties of the child object get merged and not just the child object itself.

I think you have to go with your own extend function.

Upvotes: 1

sinsedrix
sinsedrix

Reputation: 4775

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

Upvotes: 1

Related Questions