jQuery | extend() method
This extend() Method in jQuery is used to merge the contents of two or more objects together into the first object.
Syntax:
jQuery.extend( [deep ], target, object1 [, objectN ] )
Parameters: The extend() method accepts four parameter that is mentioned above and described below:
- deep: This parameter is the merge becomes recursive .
- target: This parameter is the object to extend. It will receive the new properties.
- object1: This parameter is the object containing additional properties to merge in.
- object1: This parameter is an additional objects containing properties to merge in.
Return Value: It returns the object after merging.
Below examples illustrate the use of extend() method in jQuery:
Example 1: In this example, the extend() method merge two objects in one.
<!DOCTYPE html> < html > < head > < meta charset = "utf-8" > < title >JQuery | extend() method</ title > < script src = "https://code.jquery.com/jquery-3.4.1.js" > </ script > </ head > < body style = "text-align:center;" > < h1 style = "color: green" > w3wiki </ h1 > < h3 >JQuery | extend() method</ h3 > < p >Merge two objects in One object.</ p > < p id = "Beginner" > </ p > < script > var value1 = { Beginner1: 0, Beginner2: { topic1: 52, topic2: 100 }, Beginner3: 97 }; var value2 = { Beginner2: { topic1: 200 }, Beginner4: 100 }; // Merge value2 into value1 $.extend( value1, value2 ); // Assuming JSON.stringify - not available in IE< 8 $( "#Beginner" ).append( JSON.stringify( value1 ) ); </script> </ body > </ html > |
Output:
Example 2: In this example, the extend() method merge two objects, without modifying any object.
<!DOCTYPE html> < html > < head > < meta charset = "utf-8" > < title >JQuery | extend() method</ title > < script src = "https://code.jquery.com/jquery-3.4.1.js" ></ script > </ head > < body style = "text-align:center;" > < h1 style = "color: green" > w3wiki </ h1 > < h3 >JQuery | extend() method</ h3 > < p >Merge two objects, without modifying any object.</ p > < p id = "Beginner" > </ p > < script > var Object_1 = { bool_Val: false, num: 5, name: "shubham" }; var Object_2 = { bool_Val: true, name: "SHUBHAM" }; // Merge Object_1 and Object_2, without modifying Object_1 var Object_3 = $.extend( {}, Object_1, Object_2 ); // Assuming JSON.stringify - not available in IE< 8 $( "#Beginner" ).append( "<b>Object_1 : </ b >" + JSON.stringify( Object_1 ) + "< br >" ); $( "#Beginner" ).append( "< b >Object_2 : </ b >" + JSON.stringify( Object_2 ) + "< br >" ); $( "#Beginner" ).append( "< b >Object_3 : </ b >" + JSON.stringify( Object_3 ) + "< br >" ); </ script > </ body > </ html > |
Output:
Contact Us