Skip to content
Advertisement

How to define an array with conditional elements in react

I have a arry called a tableFilterFields like this:

 const tableFilterFields = [
    {
      label: "اfrom",
      name: "StartDate",
      type: FilterControls.DatePicker,
      defaultValue: new Date(new Date().setDate(new Date().getDate() - 3100)),
    }
    props.id === undefined
      ? {
          label: "عنوان شخص",
          name: "IdentityTitle",
          type: FilterControls.Input,
        },
        {
          label: "کد بورسی",
          name: "AccountCode",
          type: FilterControls.Input,
        },
         {
          label: "نماد ",
          name: "InstrumentPersianCode",
          type: FilterControls.Input,
        },
        {
      label: "نوع معامله ",
      name: "TradeSideTitle",
      type: FilterControls.Input,
        }
        
      : 


  {
            label: "نماد ",
            name: "InstrumentPersianCode",
            type: FilterControls.Input,
          },
          {
        label: "نوع معامله ",
        name: "TradeSideTitle",
        type: FilterControls.Input,
          },
      ];

I want to apply a condition that If prop was not undefined ….How should I do this?

Advertisement

Answer

It would be better to do the conditional operation outside the array definition. You can achieve this by conditionally doing push operation

if(props.id === undefined){
  tableFilterFields.push({
          label: "عنوان شخص",
          name: "IdentityTitle",
          type: FilterControls.Input,
        },
        {
          label: "کد بورسی",
          name: "AccountCode",
          type: FilterControls.Input,
        },
         {
          label: "نماد ",
          name: "InstrumentPersianCode",
          type: FilterControls.Input,
        },
        {
      label: "نوع معامله ",
      name: "TradeSideTitle",
      type: FilterControls.Input,
        })
} else {
     tableFilterFileds.push(  {
            label: "نماد ",
            name: "InstrumentPersianCode",
            type: FilterControls.Input,
          },
          {
        label: "نوع معامله ",
        name: "TradeSideTitle",
        type: FilterControls.Input,
          })
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement