Revamp the switch-case statement in JavaScript code

Is there a way to refactor this code in order to prevent repeating dailogObj.image? I would have used a return statement if it wasn't for case 5 where two assignments are required.

getDialogData(imageNum): any {

    const dailogObj = {
      image: '',
      buttonName: 'Learn More'
    };

    switch (imageNum) {
      case 1:
        dailogObj.image = '../../../assets/images/Red-Image.png';
        break;
      case 2:
        dailogObj.image = '../../../assets/images/blue-image-orgl.png';
        break;
      case 3:
        dailogObj.image = '../../../assets/images/Green-Image-2.png';
        break;
      case 4:
        dailogObj.image = '../../../assets/images/Gold-Image.png';
        break;
      case 5:
        dailogObj.image = '../../../assets/images/green-img-orgl.png';
        dailogObj.buttonName = 'Read Her Story';
        break;
      case  6:
        dailogObj.image = '../../../assets/images/Red-Image-2.png';
        break;
      case  7:
        dailogObj.image = '../../../assets/images/Blue-Image-2.png';
        break;
      case 8:
        dailogObj.image = '../../../assets/images/Gold-Image-2.png';
        break;
    }

    return dailogObj;
}

Answer №1

To enhance readability, consider separating the assignment into its own condition and utilizing an array to set the image property:

getDialogData(imageNum): any {
    const dialogObj = {
      image: '',
      buttonName: 'Learn More'
    };

    // Handle the default case if imageNum is not within the range [1..9]
    if (imageNum >=1 && imageNum <=9) {
        // Special handling for image number 5
        if (imageNum == 5) {
            dialogObj.buttonName = 'Read Her Story';
        }

        // If it falls within the range, select the appropriate image:
        var images = 
            ['../../../assets/imfages/Red-Image.png',
             '../../../assets/images/blue-image-orgl.png',
             '../../../assets/images/Green-Image-2.png',
             '../../../assets/images/Gold-Image.png',
             '../../../assets/images/green-img-orgl.png',
             '../../../assets/images/Red-Image-2.png',
             '../../../assets/images/Blue-Image-2.png',
             '../../../assets/images/Gold-Image-2.png']; 

        dialogObj.image = images[imageNum - 1];
    }
    return dialogObj;
}

Answer №2

images = {
    1: '../../../assets/pictures/Red-Photo.png',
    2: '../../../assets/pictures/blue-photo-orgl.png',
    ...
    8: '../../../assets/pictures/Gold-Picture-2.png'
};

dialogObject.image = images[imageNum];
dialogObject.buttonLabel = imageNum == 5 ? 'Explore Her Story' : 'Discover More';

You also have the option to create an additional object for storing button labels, similar to how image paths are stored.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain JSON data response in PHP with the help of jQuery

Below is the code I am using to make an AJAX call and retrieve data from another PHP file: $.post('<?php echo get_site_url(); ?>/ajax-script/',{pickup:pickup,dropoff:dropoff,km:km}, function(data){ $('#fare'). ...

Angular 5 encountering issue with @Injectable annotation causing TypeScript error

While trying to compile my code, I encountered the following error: import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable() export class TaskService { constructor(private http: Ht ...

Creating numerous duplicates of a highly nested immutable Object can be done by using a combination of spread operators

I am currently working on retrieving data from firebase/firestore using Javascript. I have created a function where I retrieve my products collection and pass this data to the React state.products by utilizing the setState() method. My objective is to tra ...

What is the process for displaying all items within an object in Ionic 3?

Perhaps my question is not very clear, but what I am attempting to do is when the Feed item in the categories screen is clicked, all companies related to Feeding will be listed on the companies screen. I am quite confused because each category may have mu ...

After successfully posting a tweet, I have not heard back from Twitter

My objective is to achieve the following on click: Share the URL and text on Twitter in a popup window Receive a response from Twitter indicating whether the tweet was successful or failed Close the popup window after the tweet is successfully pos ...

Combining the power of Kendo UI with the flexibility of Vue

Hey there everyone, I'm currently utilizing the Vue.js CLI for my project. Recently, I came across a helpful tutorial on incorporating a Jquery plugin into a webpack project at this link: . To achieve this, I installed the expose loader and added th ...

Set a value for the hidden field on the page using client-side scripting

When working with an ASP.net application, I often use Page.ClientScript.RegisterHiddenField("hf_Name", value). However, I am curious about how to override or set a new value for the same Hidden Field 'hf_Name' in the code behind. Can you provide ...

Substitute terms in a sentence according to the guidelines

Looking to transform strings based on specific rules? "Hello {{firstName}}, this is {{senderName}}." Consider the following rules: rules = { firstName: "Alex", senderName: "Tracy" } The expected output would be: "Hello Alex, this is Tracy." If yo ...

The mat-slide-toggle component does not recognize the checked binding

My angular app contains the mat-slide-toggle functionality. switchValue: {{ switch }} <br /> <mat-slide-toggle [checked]="switch" (toggleChange)="toggle()">Toggle me!</mat-slide-toggle> </div> This is how the ...

Applying conditional logic within computed properties results in a failure to update

I have two different fiddles: Fiddle A and Fiddle B (both using Vuejs version 2.2.4) In my code, I have a computed property that can be changed programmatically by utilizing the get and set methods. Expectations for the Computed Property: If the def ...

When attempting to transfer data from the parent component to child components, the data is appearing as undefined in the display

I have been working on passing data from a parent component to child components, but I keep encountering an issue where the data is showing as undefined. Below is the code snippet: Parent Component In this section, I have declared the variable part_data ...

What is the best method to erase data from an AutoComplete Box when clicking?

I have incorporated the Material UI AutoComplete component which can be found here. Below is my code snippet: <Autocomplete open={showUniSuggs} onOpen={this.props.getUniversityOptions} onChange={(event, value) => this.props.handleUniversi ...

Explore the Wikipedia API play area by searching based on the user's input

Having trouble searching Wikipedia based on user input. Initially, I suspected a cross-domain issue, but I believe .ajax should resolve that. You can view the codepen here: http://codepen.io/ekilja01/pen/pRerpb Below is my HTML: <script src="https:// ...

Converting a JavaScript string into an array or dictionary

Is there a way to transform the following string: "{u'value': {u'username': u'testeuser', u'status': 1, u'firstName': u'a', u'lastName': u'a', u'gender': u'a&a ...

Passing arrow functions for input validation rules to the Stancil component in Vue

I am attempting to implement an arrow function as input rules, similar to the setup in Vuetify at https://vuetifyjs.com/en/api/v-input/#rules. My approach involves passing rules within an array using the following code: <body> <div id="ap ...

What is the best way to dynamically update a specific value within an object based on the current state in React/Next?

I have implemented a Context API where an object is set, and when the user clicks, the state changes. I need to update a specific value with the new state value. const initialState = { notification: false, setting: false, profile: false, } exp ...

changing the css transformation into zoom and positioning

My goal is to incorporate pinch zoom and panning using hardware-accelerated CSS properties like transform: translate3d() scale3d(). After completing the gesture, I reset the transform and switch to CSS zoom along with absolute positioning. This method ensu ...

Next.js Error: The text displayed on the page differs from the HTML rendered by the server

Currently, I am facing an issue with the error "Error: Text content does not match server-rendered HTML." Here is my scenario - I have received a dateTime from an API, for example '2022-12-25T11:22:37.000Z', and I want to display it on a compone ...

Is the parent node of the input element the input element itself?

When working with a DOM object obj of type <input>, I encountered an issue where attempting to obtain its parent node using obj.parentNode resulted in the same obj being returned. Is this behavior specific to <input> objects? What other types o ...

Using the factory pattern in a Node.js (Express) application

As I delved into the realm of design patterns, I found myself drawn to the factory pattern. However, as I perused through code written by others, I noticed that this particular pattern wasn't as prevalent, especially in newer stacks. Take for example ...