Merge Two Json Objects Into One By Jquery


JSON or Javascript Object Notation is a useful form of storing and passing data. Recently I used jQuery to merge two JSON objects into one by using the $.extend() method. Here is how I did it.

  var passData,fixedData;
  fixedData = {
                'start_date_1': $('#start_date_1').val(),
                'start_date_2': $('#start_date_2').val(),
                'end_date_1': $('#end_date_1').val(),
                'end_date_2': $('#end_date_2').val(),
               };
   passData = {
                 'mode': 'get_total_visits',
              };  
                     
   $.extend(passData,fixedData);

Here fixedData and passData are two javascript variables holding the two JSON objects. $.extend() merges the fixedData into passData. So now passData contains the full JSON values.

Here is what the output will be:
passData = {
                'start_date_1': $('#start_date_1').val(),
                'start_date_2': $('#start_date_2').val(),
                'end_date_1': $('#end_date_1').val(),
                'end_date_2': $('#end_date_2').val(),
     'mode': 'get_total_visits',
               };