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)
}

.
.
.
.
3

There are 3 best solutions below

3
MauriceNino On BEST ANSWER

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);
}
0
kiratot On

I would suggest using a data structure where you can save the data you want to check on, and also if you're checking the same condition for every field then implement the logic in a function. Assuming you're using an array as the data structure the code would look like this:

const appendField = (field) => {
if (field  != '' && field  != null && field  != undefined)
//here you can do something in this case append(field)
}
// myArr is the array where you have the data you want to check
myArr.forEach(field => appendField(field))
0
jamesmallred On

Looping over the keys in the object and checking the value for each unique key could be a good way to go. If you need to maintain the order of the keys, the forEach method allows you to pass in an index as well. i in the example.

const appendValues = (data) => {
    const keys = Object.keys(data);

    keys.forEach((key, i) => {
        if (data[key]) {
            // Append logic if value
            append(data[key]);
        } else {
           // Logic if no value
        }
    })
};