score:4

Accepted answer
const prepareDataForApi = (formData) => {
  const newFormData = Object.assign({}, formData); // optional if passed cloned copy of formData object or you can also use lodash cloneDeep
  newFormData.data = {
    reasonArray:[]
  };

  Object.keys(newFormData.reasons).forEach(key => {
    if(newFormData.reasons[key]){
      newFormData.data.reasonArray.push({reason: key})
    }
  });

  delete newFormData.reasons;

  return newFormData;
}

score:0

const [formState, setFormState] = React.useState({...}):

// Runs every time weightLoss is changed
React.useEffect(() => {
  let newReasonArray 
  if (formState.weightLoss) {
    newReasonArray = [...formState.reasonArray]; // So we dont mutate state
    newReasonArray.push({reason: 'weightLoss'});
  } else {
    // If you want to remove it from the array if its unchecked
    newReasonArray = [...formState.reasonArray];
    newReasonArray.filter((reason) => (reason.reason != 'weightLoss'));
  }

  console.log(newReasonArray) // Test if it is updated correctly

  // Set the state with the new array
  setFormState({...formState, data: { reasonArray: newReasonArray }});
}, [formState.weightLoss]);

Related Query

More Query from same tag