merge two or more objects

Description

You can merge two or more objects with the .extend() method. It combines the properties of one or more objects into a target object. In the next example, obj1 receives the properties of obj2 and obj3:

Example


<!DOCTYPE html> 
<html>
<head> 
    <script src="http://yourServer.com/jQuery/jquery.min.js"></script> 
    <script> 
        var obj1 =  {"1":"property 1"}; 
        var obj2 =  {"2":"property 2"}; 
        var obj3 =  {"3":"property 3"};
        $.extend(obj1, obj2, obj3);<!-- w  w  w .  j a v a  2 s .c  o  m-->
        console.log(obj1["3"]); // displays  property  3
    </script> 
</head> 
<body> 
  <p>Your tags here</p>
</body> 
</html>

Click to view the demo

Note

.extend() can clone JavaScript objects.

var clonedObject = $.extend({}, anObject);

$.extend() accepts an additional first argument for doing a deep merge of objects. You can use this to do a deep clone of objects as well:

var clonedObject = $.extend(true, {}, anObject);




















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities