jQuery.extend()
Method
Example
Iterate over array elements and modify the first object.
<div id="log"></div>
<script>
$(function () {
var object1 = {
apple: 0,
banana: {weight: 52, price: 100},
cherry: 97
};
var object2 = {
banana: {price: 200},
durian: 100
};
/* Merge object2 into object1 */
$.extend(object1, object2);
var printObj = typeof JSON != "undefined" ? JSON.stringify : function(obj) {
var arr = [];
$.each(obj, function(key, val) {
var next = key + ": ";
next += $.isPlainObject(val) ? printObj(val) : val;
arr.push( next );
});
return "{ " + arr.join(", ") + " }";
};
$("#log").append( printObj(object1) );
})
</script>
Definition and Usage
The jQuery.extend()
function is used to merge the contents of one or more objects into the target object.
Note: 1. If only one argument is specified for $.extend()
, it means the target
parameter is omitted. In this case, the target
is the jQuery object itself. This way, we can add new functions to the global jQuery object.
Syntax
Indicates whether to perform a deep merge.
Warning: Passing false
as the first parameter is not supported.
Parameter | Description |
---|---|
deep | Optional. Boolean type indicating whether to perform a deep merge of objects, default is false . If this value is true and multiple objects have a property with the same name that is also an object, the properties of that "property object" will also be merged. |
target | Object type. The target object to which the properties of other objects will be appended. |
object1 | Optional. Object type. The first object to be merged. |
objectN | Optional. Object type. The Nth object to be merged. |
More Examples
Merge defaults
and options
Objects