Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

jQuery.extend() method

jQuery.extend() method

jQuery Miscellaneous MethodsjQuery Miscellaneous Methods

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

Try it »


Definition and Usage

The jQuery.extend() function is used to merge the contents of one or more objects into a target object.

**Note:** 1. If only one argument is specified for $.extend(), it means the target argument is omitted. In that case, target is the jQuery object itself. In this way, we can add new functions to the global jQuery object.
2. If multiple objects have the same property, the latter overrides the former's property value.


Syntax

$

.extend( target [, object1 ] [, objectN ] )

Indicates whether to merge deeply

$

.extend( [deep ], target, object1 [, objectN ] )

**Warning: ** Passing false as the first argument is not supported.

Parameters Description
deep Optional. Boolean type: Indicates whether to deeply merge objects, defaulting to false. If the value is true and a same-named property in multiple objects is also an object, the properties of that "property object" are merged as well.
target Object type: The target object to which the members 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 two objects recursively
Merge two objects recursively and modify the first object.

Merge the defaults and options objects
Merge the defaults and options objects without modifying the defaults object. This is a common plugin development pattern.


jQuery Miscellaneous MethodsjQuery Miscellaneous Methods