我正在尝试使用if / else,但无法弄清楚语法哪里出问题了。我希望payload
仅在school_ids
不是role
的情况下提交p_admin
。谢谢您的帮助!
const createUser = (payload) => request.postJSON(
'/register',
excludeObjNullValue({
username: payload.username,
email: payload.email,
password: payload.password,
first_name: payload.firstName,
last_name: payload.lastName,
role: payload.role,
district_id: payload.districtId,
if (role !== 'p_admin'){
school_ids: payload.schoolIds
}
})
);
最佳答案
我看到2-3个选项,具体取决于您的excludeObjNullValue
函数:
您可以将该表达式分解为几个语句,或者
或使用属性扩展表示法和条件运算符,或
如果excludeObjNullValue
符合名称的含义,则可以使用不带扩展符的条件,并依靠excludeObjNullValue
排除它
选项3可能是您最好的选择,但我按顺序给他们:
选项1:多陈述方式:
const createUser = (payload) => {
const options = {
username: payload.username,
email: payload.email,
password: payload.password,
first_name: payload.firstName,
last_name: payload.lastName,
role: payload.role,
district_id: payload.districtId,
};
if (role !== 'p_admin') {
options.school_ids = payload.schoolIds;
}
return request.postJSON('/register', excludeObjNullValue(options));
};
选项2:财产价差和条件运算符
Property spread是第3阶段的建议,但已经在Chrome和Firefox中提供了对它的支持,如果要进行编译,则可以告诉您的编译器予以支持。看起来像这样:
const createUser = (payload) => request.postJSON(
'/register',
excludeObjNullValue({
username: payload.username,
email: payload.email,
password: payload.password,
first_name: payload.firstName,
last_name: payload.lastName,
role: payload.role,
district_id: payload.districtId,
{...(role !== 'p_admin' ? {school_ids: payload.schoolIds} : {}}
}
})
);
即使支持,这是否是个好主意。 :-)它确实会短暂创建一个额外的对象和迭代器。
选项3:依靠
excludeObjNullValue
排除具有null
值的属性:如果确实如其名称所示,那么如果我们赋予它
school_ids
值,它将删除null
。所以:const createUser = (payload) => request.postJSON(
'/register',
excludeObjNullValue({
username: payload.username,
email: payload.email,
password: payload.password,
first_name: payload.firstName,
last_name: payload.lastName,
role: payload.role,
district_id: payload.districtId,
school_ids: role !== 'p_admin' ? payload.schoolIds : null
}
})
);
关于javascript - JS中的if语句语法错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47719013/