1

In Javascript I have a collection of objects, whose values I'm storing in variable

var filters = {
    BeginDate: $("#BeginDateRange").val(),
    EndDate: $("#EndDateRange").val(),
    ListOfCodes: $("#ListOfCodes").val(),
    //ListOfCodes: $("#ListOfCodes").val().join(),
    ...
}

Based on where I use the collection, some of its objects remain 'undefined', and it is intended.

ListOfCodes above is an array of string values, and I want to pass it to the binder as a single comma-separated string (e.g ["1"], ["2"] -> "1,2")

I was able to make a use of .join(), and it worked successfully. However, I found later that the code will crash if the .join() does not have a value to join.

Is there a way to apply .join() INSIDE the collection to the variable ONLY if it has value? Something like

var filters = {
    BeginDate: $("#BeginDateRange").val(),
    EndDate: $("#EndDateRange").val(),
    ListOfCodes: if( $("#ListOfCodes").val() )
                     {$("#ListOfCodes").val().join()} 
                  else
                      {$("#ListOfCodes").val()}    //value remains undefined
    ,
    ...
}

EDIT: I ask about the possibility of applying .join() method inside the collection, not checking for empty values.

Vadzim Savenok
  • 930
  • 3
  • 14
  • 37

1 Answers1

2

Just moving this as an answer.

What about a ternary statement?

ListOfCodes: ($("#ListOfCodes").val()) ? $("#ListOfCodes").val().join() : null

ReyHaynes
  • 2,932
  • 1
  • 15
  • 22