我正在尝试使用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
}
})
);
答案 0 :(得分:4)
我会看到2-3个选项,具体取决于您的excludeObjNullValue
功能:
您可以将该表达式分解为几个语句,或者
或使用属性扩展表示法和条件运算符,或
如果excludeObjNullValue
符合名称的建议,您可以使用条件而不使用点差表示法,并依靠excludeObjNullValue
将其排除
选项3可能是您最好的选择,但我会按顺序给出它们:
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));
};
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} : {}}
}
})
);
即使您的电话受到支持,这是否是一个好主意。 :-)它会简要地创建一个额外的对象和迭代器。
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
}
})
);
答案 1 :(得分:1)
您无法在对象声明中编写if
语句。您还需要为箭头函数明确定义body。所以你可以做类似
const createUser = (payload) => {
const obj = {
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(obj.role !== 'p_admin') {
obj.school_ids = payload.schoolIds
}
return request.postJSON('/register', excludeObjNullValue(obj));
}