Add list options based on the specific conditions

When working with dynamic dropdowns or category lists, it’s common to filter a set of allowed values and conditionally add extra options based on user input. In JavaScript, this can be achieved by first filtering the base categories and then appending the required option dynamically from the original list to maintain consistency. This approach ensures no hard-coded labels, prevents duplicates, and keeps the UI data structure intact.

In the below code snippet, here we want to add the ‘ jj_cm_library.CATEGORY.CS_DELIVERY_OR_INSTALL_FOLLOWUP’ if the current value of ‘ticketTypeValue == 26′.

filteredCategories = listValues.filter(category =>

                    [

                        jj_cm_library.CATEGORY.APOGEE,

                        jj_cm_library.CATEGORY.SPS_API,

                        jj_cm_library.CATEGORY.CS_DAMAGED_PRODUCT,

                        // jj_cm_library.CATEGORY.CS_DELIVERY_OR_INSTALL_FOLLOWUP,

                        jj_cm_library.CATEGORY.CS_EXCHANGE,

                        jj_cm_library.CATEGORY.WS_PROPERTYDAMAGE,

                        jj_cm_library.CATEGORY.CS_REFUND,

                        jj_cm_library.CATEGORY.CS_RETURN,

                        jj_cm_library.CATEGORY.CS_CREDIT_MEMO

                    ].includes(category.value.toString())

                );

                if (checkForParameter(ticketTypeValue) && ticketTypeValue === ’26’) {

                    const extraOption = listValues.find(opt =>

                        String(opt.value) === String(jj_cm_library.CATEGORY.CS_DELIVERY_OR_INSTALL_FOLLOWUP)

                    );

                    if (extraOption && !filteredCategories.some(opt => String(opt.value) === String(extraOption.value))) {

                        filteredCategories.push(extraOption);

                    }

                }

This pattern filters a predefined set of category values from listValues, ensuring the resulting filteredCategories preserves each option’s { text, value } structure. It then conditionally appends the “Delivery or Install Follow-up” option only when ticketTypeValue equals '26', sourcing the full option object dynamically to avoid hard-coding and prevent duplicates.

Leave a comment

Your email address will not be published. Required fields are marked *