Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update tuples in Javascript?

(Not sure if I am using the correct terminology, in Python that is called a tuple. Hope it makes sense.)

I would like to refactor the following method. The only difference is the enddate/startdate respectively, therefore 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 put the common values as a tuple together:

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

Then add the one additional keypair in there: (However this step seems to be completely off, how do i achieve it?)

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

and then pass the whole tuple to the function:

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

is this possible?

like image 230
Houman Avatar asked May 28 '26 15:05

Houman


2 Answers

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

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

You are just setting an object's property.

Note: options.endDate = new Date(); (dot notation) would also work, however it does not work if the property you're adding to the object contains spaces, operators, or other special chars.

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

like image 196
Benjamin Gruenbaum Avatar answered May 30 '26 05:05

Benjamin Gruenbaum


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

$.extend(options, { endDate: new Date() });
like image 21
James McLaughlin Avatar answered May 30 '26 04:05

James McLaughlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!