What is $.extend() in jQuery

What is $.extend() in jQuery

Have you ever come across a requirement in which you need merge many objects into one object? Okay let me clarify the question in simpler words. Assume you have two objects as shown below. "object1" is defined as in the following:

 var object1 = {
     red: 0,
      blue: { lightblue: 24, darkblue: 12 },
      black: 17
};

And another object is "object2" as in the following:

 var object2 = {
            white: 200,
            blue: {lightblue:40}
        };

Let us say you need to merge object2 into object1. Here merge means merging properties of object2 into object1. You can do this in jQuery using the extend() function.

$.extend(object1object2);
      console.log(object1);-+

Now if you proceed to and view console you see following output. As you can see value for "blue" property in "object1" has been changed with the value of object2's "blue" property.



This is the way that "$.bind()" merges two objects in jQuery. There could be another scenario in which you want to merge objects recursively. Recursively means that each property value that is unique in the target object will be persisted. For recursive binding you need to set the first parameter to "True".

$.extend(true,object1object2);
      console.log(object1);

In the output you can see that now the blue property of object1 has both darkblue and lightblue. The value of darkblue has been modified with object2's property value. 
Property

You can merge more than two objects as in the following. Always remember that "$.bind" returns the target object as output as in the following:

var object1 = {
    red: 0,
    blue: { lightblue: 24, darkblue: 12 },
    black: 17
};

var object2 = {
   white: 200,
    blue: { lightblue: 40 }
 };

var object3 =
   {
        yellow: 234
   };
var targetresult = $.extend({}, object1object2object3);
console.log(targetresult);

In this way you can merge objects in JavaScript using the jQuery "$.bind()" function. I hope you find this article useful. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all