Search code examples
javascriptarraysreactjsreact-hooks

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: "IdentityTitle",
          name: "IdentityTitle",
          type: FilterControls.Input,
        },
        {
          label: "AccountCode",
          name: "AccountCode",
          type: FilterControls.Input,
        },
         {
          label: "InstrumentPersianCode",
          name: "InstrumentPersianCode",
          type: FilterControls.Input,
        },
        {
      label: "TradeSideTitle ",
      name: "TradeSideTitle",
      type: FilterControls.Input,
        }
        
      : 


  {
            label: "InstrumentPersianCode",
            name: "InstrumentPersianCode",
            type: FilterControls.Input,
          },
          {
        label: "TradeSideTitle",
        name: "TradeSideTitle",
        type: FilterControls.Input,
          },
      ];

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


Solution

  • 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,
              })
    }