How to use if condition inside an object in react

Viewed 23

I'm trying to pass some data as payload to the api and I'm struggling to put condition inside of the object. I have an object called payload and I want to pass it in the api by checking the value of the state called profession.

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

as you can see in the top I want to pass the entire key and value if the condition is true. If the profession is not student I don't even pass the universityname key.

1 Answers

You should use a combination of ternary and spread operator

 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 have explained something similar here

An example:

let car = "BMW";

const result = {

  ...(car === "BMW" ? {
    make: "Germany"
  } : {
    make: "other"
  })

};

console.log(result);

Related