How do I update tuples in Javascript?

(Not sure if I'm using the correct terminology in Python, which is called a tuple. I hope this makes sense.)

I would like to refactor the following method. The only difference is enddate/startdate

accordingly, so there is no need to repeat the code.

function datepicker_reload(source, isPast){
    if(isPast){
        $(source).find('.date_picker').datepicker({ 
            endDate: new Date(),
            format: $('#locale').text(), 
            weekStart:1, 
            calendarWeeks:'True',   
            autoclose: 'True', 
            todayHighlight: 'True' 
        });
    }
    else{
        $(source).find('.date_picker').datepicker({
            startDate: new Date(), 
            format: $('#locale').text(), 
            weekStart:1, 
            calendarWeeks:'True',   
            autoclose: 'True', 
            todayHighlight: 'True' 
        });
    }
}

      

I was wondering if I could concatenate common values ​​as a tuple:

var options = { format: $('#locale').text(), 
            weekStart:1, 
            calendarWeeks:'True',   
            autoclose: 'True', 
            todayHighlight: 'True'  };

      

Then add another key pair: (However, this step seems to be completely disabled, how do I achieve it?)

if(isPast)
   options += {endDate: new Date()}
else
   options += {startDate: new Date()}

      

and then pass the whole set of functions:

$(source).find('.date_picker').datepicker(options);

      

Is it possible?

+3


source to share


3 answers


The correct syntax in javascript for what you are trying to do is:

if(isPast){
   options["endDate"] = new Date();
}else{
   options["startDate"] = new Date();
}

      

You just set a property on the object.



Note: options.endDate = new Date();

(dot notation) will also work, however it will not work if the property you are adding to the object contains spaces, operators, or other special characters.

Note 2: I am assuming you don't really want to clone the object, but just add a property to it, javascript objects are mutable.

+3


source


With jQuery, the usual way to do this is to use extend :



$.extend(options, { endDate: new Date() });

      

+1


source


You can use $.extend

jquery method

function datepicker_reload(source, isPast){
    var options = { format: $('#locale').text(), 
            weekStart:1, 
            calendarWeeks:'True',   
            autoclose: 'True', 
            todayHighlight: 'True'  };

    var newDate = new Date();

    if(isPast){
        $.extend(options, { endDate: newDate } );
    } else {
        $.extend(options, { startDate: newDate } );
    }

    $(source).find('.date_picker').datepicker( options );
}

      

-1


source







All Articles