Search code examples
typescriptconditional-statementsdropdowncategories

Is there a way to export a value conditionally on a selection?


I have some very basic Typescript code:

export const defaultListingFormValues = {
  itemWeight: 1
}

Is there a way to change the default value of itemWeight to be conditional based on an item's category selected via a dropdown for a listing form?

Something like dress = 0.5, heels = 1, boots = 2, etc. depending on which option is selected?


Solution

  • You can define your defaultListingFormValues with category objects as { itemWeight: 1, dress: { itemWeight: 1 },... }.

    And use it with category value from dropdown as below. Here categoryFromDropDown holds category from dropdown i.e. dress. Used condition so if any category is not defined then it will return default value.

    let defaultValue = defaultListingFormValues[categoryFromDropDown] ?
          defaultListingFormValues[categoryFromDropDown].itemWeight :
          defaultListingFormValues.itemWeight;
    

    Try it below. For demo export & import statements are commented.

    // export const defaultListingFormValues = {
    const defaultListingFormValues = {
      itemWeight: 1,
      dress: {
        itemWeight: 0.5
      },
      heels: {
        itemWeight: 1
      },
      boots: {
        itemWeight: 2
      }
    }
    
    // When you access 
    // import defaultListingFormValues from '...';
    let categoryFromDropDown = 'dress';
    let defaultValue = defaultListingFormValues[categoryFromDropDown] ?
      defaultListingFormValues[categoryFromDropDown].itemWeight :
      defaultListingFormValues.itemWeight;
      
    console.log(defaultValue);
    
    // category which is not present in defaultListingFormValues.
    categoryFromDropDown = 'aaa';
    defaultValue = defaultListingFormValues[categoryFromDropDown] ?
      defaultListingFormValues[categoryFromDropDown].itemWeight :
      defaultListingFormValues.itemWeight;
      
    console.log(defaultValue);