What Is $.extend() In jQuery

JQuery extend merges two objects. In this article, learn how to merge objects using the extend function in jQuery.

What is $.extend() in jQuery

 
Have you ever come across a requirement in which you need to 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,
  1.  var object1 = {  
  2.      red: 0,  
  3.       blue: { lightblue: 24, darkblue: 12 },  
  4.       black: 17  
  5. };  
And another object is "object2" as in the following,
  1. var object2 = {  
  2.            white: 200,  
  3.            blue: {lightblue:40}  
  4.        };  
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,
  1. $.extend(object1, object2);  
  2.       console.log(object1);-+  
Now if you proceed and view the console you see the following output. As you can see, the 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".
  1. $.extend(true,object1, object2);  
  2.       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,
  1. var object1 = {  
  2.     red: 0,  
  3.     blue: { lightblue: 24, darkblue: 12 },  
  4.     black: 17  
  5. };  
  6.   
  7. var object2 = {  
  8.    white: 200,  
  9.     blue: { lightblue: 40 }  
  10.  };  
  11.   
  12. var object3 =  
  13.    {  
  14.         yellow: 234  
  15.    };  
  16. var targetresult = $.extend({}, object1, object2, object3);  
  17. 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.