当字段列表非常大时,使用 javascript 中的 if 条件计算是否填充字段的有效方法

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

我有一个表单,其中有很多字段,考虑可能有 100 个。所有字段都不相同,例如 StartTime DateTime EndTime Value etc.。用户可以填写他们想要的任何字段,并将其余字段保持黑色。

现在,在 Javascript or Node.js 方面,我需要检查是否为每个字段填充了字段,然后基于此我需要创建一个 XML 文件。截至目前,我正在尝试使用 if 条件检查是否填充了每个字段。如果我继续使用这种方法,那么我需要编写 100 IF 条件来管理所有 100 个耗时且冗余的字段。

我很好奇是否有更好的方法。我尝试搜索但找不到任何相关的 post 这给了我一些想法。如果重复了真的很抱歉。

有没有人有更好的主意?

截至目前,我正在检查如下内容:

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

.
.
.
.

你可以这样做

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

appendIf(StartTime);
appendIf(DateTime);
appendIf(EndTime);
appendIf(Value);

如果所有值都在一个数组或对象中,您也可以只循环遍历它:

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

我建议使用一种数据结构,您可以在其中保存要检查的数据,而且如果您要检查每个字段的相同条件,则在函数中实现逻辑。假设您使用数组作为数据结构,代码将如下所示:

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

遍历对象中的键并检查每个唯一键的值可能是一个不错的方法。如果您需要维护键的顺序,forEach 方法还允许您传入一个索引。 i 在示例中。

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