jQuery : Proper use of $.extend

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

Keep in mind that the target object (first argument) will be modified, and will also be returned from $.extend().
If, however, you want to preserve both of the original objects, you can do so by passing an empty object as the target:

var object = $.extend({}, object1, object2);


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 );

Output is:



The merge performed by $.extend() is not recursive by default; if a property of the first object is itself an object or array, it will be completely overwritten by a property with the same key in the second or subsequent object.
The values are not merged. This can be seen in the example below by examining the value of banana. However, by passing true for the first function argument, objects will be recursively merged.

Reference: http://api.jquery.com/jQuery.extend/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s