javascriptnode.jsif-statementundefinedxml-builder

Efficient way to calculate if the fields are populated using the if condition in javascript when the field list is very large


I have a form which has lot of fields consider maybe 100. All of the fields are different such as it could be StartTime DateTime EndTime Value etc.. User can fill whichever the field they want and keep the remaining fields black.

Now on the Javascript or Node.js side I need to check if the fields are populated for each of them then based on that I need to create an XML file. As of now, I am trying to check if each field is populated using the if the condition. If I proceed in this method then I need to write 100 IF condition to manage all 100 fields which are time-consuming and redundant.

I was just curious if there is any better way of doing it. I tried searching but could not find any relevant post which gives me some sort of idea. If it's duplicate then I am really sorry.

Does anyone have a better idea?

As of now, I am checking something like this:

if(StartTime  != '' && StartTime  != null && StartTime  != undefined)
{
    append(StartTime)
}

if(DateTime  != '' && DateTime  != null && DateTime  != undefine)
{
    append(DateTime)
}
    
if(EndTime  != '' && EndTime  != null && EndTime  != undefine)
{
    append(EndTime)
}

if(Value  != '' && Value  != null && Value  != undefine)
{
    append(Value)
}

.
.
.
.

Solution

  • You could do something like this

    const appendIf = () => {
       if(val != '' && val != null && val != undefine) {
          append(val);
       }
    };
    
    appendIf(StartTime);
    appendIf(DateTime);
    appendIf(EndTime);
    appendIf(Value);
    

    If all the values are in an array or object, you could also just loop over that:

    for(/* whatever for loop is needed*/) {
       appendIf(currentValue);
    }