Wednesday, May 2, 2012

jQuery .extend() - merge objects


The jQuery .extend() method merge objects into a target object. The example below, object1 receives the properties of object2 and object3.

jQuery .extend() - merge objects


<!doctype html>
<head>
 <title>Mobile-Web-App: jQuery.extend</title>
 <meta charset="utf-8">
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
 <script type="text/javascript">

  $(document).ready(function(){

   var object1 = {"prop_a": "Property A"};
   var object2 = {"prop_b": 123.001};
   var object3 = {"prop_c": object2};
   
   document.writeln("<p><b>$.extend</b></p>");

   document.writeln("<p>object1:</p>");
   $.each(object1, function(i, val) {
    document.writeln("<p>i: " + i  + " / v: " + val + "</p>");
   });
   
   document.writeln("<p>object2:</p>");
   $.each(object2, function(i, val) {
    document.writeln("<p>i: " + i  + " / v: " + val + "</p>");
   });

   document.writeln("<p>object3:</p>");
   $.each(object3, function(i, val) {
    document.writeln("<p>i: " + i  + " / v: " + val + "</p>");
   });
   
   document.writeln("<p><b>$.extend(object1, object2, object3)</b></p>");
   $.extend(object1, object2, object3);
   
   document.writeln("<p>object1:</p>");
   $.each(object1, function(i, val) {
    document.writeln("<p>i: " + i  + " / v: " + val + "</p>");
   });

  });
 </script> 
 
</head>
<body>
</body>
</html>


No comments:

Post a Comment