我试图将一些数据作为有效负载传递给api,我很难将条件放入对象中。我有一个名为payload
的对象,我想通过检查名为profession
的状态值将其传递给api。
const payload ={
name: registerData.fullname,
password: registerData.password,
confirm_password: registerData.confirmPassword,
email: registerData.email,
additional_info: {
profession == "Student" ? (
universityname: values.universityname,
course: values.course,
start_year: values.start_year,
end_year: values.end_year, ) :
(professorUniversity: values.professorUniversity,
department: values.department,
organizationName: values.organizationName,
organizationLocation: values.organizationLocation,
investorCompany: values.investorCompany,
investorCompanyWebsite: values.investorCompanyWebsite,
companyName: values.companyName,
govtSector: values.govtSector,
govtDesignation: values.govtDesignation,
)
},
};
// I'm passing the payload in the api.
api.post("some-url/register", payload);
正如你在上面看到的,如果条件为真,我想传递整个键和值。如果profession
不是student,我甚至不传递universityname
键。
1条答案
按热度按时间mzillmmw1#
您应该使用ternary和spread operator的组合
我已经解释了类似于here的内容
举个例子: