Making if-else statements easier

Greetings! I have a JSON data that looks like this:

{
    "details":
        {
            "data1": 
                {
                    "monthToDate":1000,                   
                    "firstLastMonth":"December",
                    "firstLastMonthAmount":5000,
                    "secondLastMonth":"November",
                    "secondLastMonthAmount":12000
                },
            "data2":
                {
                    "monthToDate":4000,                   
                    "firstLastMonth":"December",
                    "firstLastMonthAmount":10000,
                    "secondLastMonth":"November",
                    "secondLastMonthAmount":15000
                },
           "data3":
                {
                    "monthToDate":2000,                   
                    "firstLastMonth":"December",
                    "firstLastMonthAmount":8000,
                    "secondLastMonth":"November",
                    "secondLastMonthAmount":12000
                }
        }   
}

Additionally, I have some TypeScript if statements as shown below,

....
Object.values(data.details.data1).map(obj => {
                switch (obj) {
                    case 'January':
                        xAxisTranslatedArray.push(this.JAN);
                        break;
                    case 'February':
                        xAxisTranslatedArray.push(this.FEB);
                        break;
                    case 'March':
                        xAxisTranslatedArray.push(this.MAR);
                        break;
                    case 'April':
                        xAxisTranslatedArray.push(this.APR);
                        break;
                    case 'May':
                        xAxisTranslatedArray.push(this.MAY);
                        break;
                    case 'June':
                        xAxisTranslatedArray.push(this.JUN);
                        break;
                    case 'July':
                        xAxisTranslatedArray.push(this.JUL);
                        break;
                    case 'August':
                        xAxisTranslatedArray.push(this.AUG);
                        break;
                    case 'September':
                        xAxisTranslatedArray.push(this.SEP);
                        break;
                    case 'October':
                        xAxisTranslatedArray.push(this.OCT);
                        break;
                    case 'November':
                        xAxisTranslatedArray.push(this.NOV);
                         break;
                    case 'December':
                        xAxisTranslatedArray.push(this.DEC);
                        break;
                }
            });

I am making use of lodash, Highcharts, and i18n translations in my project. Each this.MONTH represents an i18n key. Since direct translation is not possible, I am storing these values in an array to pass them to the X-axis of the Highchart. The current if-else structure seems lengthy and repetitive. Is there a more efficient way to handle this? Thank you for your assistance.

Answer №1

An efficient way to handle this is by creating a separate map object:

const months = {
    January: this.JAN,
    February: this.FEB,
    March: this.MAR,
    // and so on...
}

Object.values(data.details.data1).forEach(obj => {
    if (months[obj]) {
        xAxisTranslatedArray.push(months[obj]);
    }
});

Alternatively, you can optimize the code by replacing the if statement with a filter method:

Object.values(data.details.data1)
    .filter(obj => months[obj])
    .forEach(obj => xAxisTranslatedArray.push(months[obj]));

It's worth noting that I'm using forEach instead of map. Since you are only iterating over an array and not modifying it, forEach is the more appropriate choice in this scenario.

Answer №2

To incorporate a map definition, follow this example:

let translation = {};
translation['January'] = this.JAN;
... // additional definitions.


Object.values(data.details.data1).forEach(item => {
              if(translation[item]){
                  translatedXAxis.push(translation[item]);
              });

Answer №3

It appears that the key you are looking for is derived from obj's first three letters in uppercase. You can achieve this by following:

var monthArray = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
Object.values( data.details.data1 ).forEach(obj => {
   if ( monthArray.indexOf( obj ) != -1 )
   {
      xAxisTranslatedArray.push(this[ obj.substring(0,3).toUpperCase() ]);
   }
});

Answer №4

To extract the first three characters, utilize bracket notation.

For this task, employ either the substring or slice methods.

Ensure that the variable obj is indeed a string.

var names = [ "John", "Jane", "Jim", "Jack", "Jill" ];
if(typeof obj === 'string' && names.includes(obj))
    selectedNames.push(this[obj.substring(0,3).toUpperCase()]);

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 the key's value from a JSON object that is nested within another

Managing a complex data structure is crucial in programming. How can I efficiently retrieve specific values using known keys from this nested data? Take, for instance: var data = { code: 42, items: [{ id: 1, category: [{ ...

What is the best approach to incorporate Column Reordering in react-data-grid?

Within my REACT application, I have incorporated the npm package react-data-grid. They offer a sample showcasing Column Reordering on their website. I wish to replicate this functionality in my own code. Upon reviewing their source code, I am puzzled abou ...

Interacting with an XML file contained within a PHP variable using jQuery

I'm pretty new to programming, so please be patient with me =] Currently, I am working on passing a string from the user to an API using PHP. The API then responds with an XML file, which I store under $response. So far, everything is running smoothl ...

There is no index signature containing a parameter of type 'string' within the type '{ appointments: { label: string; id: number; minWidth: number; }[]; }'

Just getting started with React and Typescript. I'm attempting to extract data from the configuration file based on the input(props), but it seems like Typescript is throwing errors. Any suggestions on how to tackle this issue? config.json { "t ...

The spinning loading wheel on Firefox persists even after submitting the iFrame

I have encountered a strange issue with Firefox that I can't seem to figure out. In my system, AJAX is used to send data to a PHP API. However, when file uploads are involved, Firefox does not use XMLHttpRequest() and instead reverts to submitting the ...

Developing middleware for managing event handlers

Scenario: I am tasked with managing multiple events that necessitate an "available client". Therefore, in each event handler, my first step is to attempt to acquire an available client. If no client is available, I will send a "Service unavailable" messag ...

Exploring the Power of React's Ref API

Currently, I am following tutorials on Udemy by Max where he discusses how to work with Ref Api's in React 16.3. In one of the lectures, he demonstrated creating a ref inside a container class, not App.js, using this.lastref = React.createRef();. He ...

Next.js experiences slowdown when initializing props on the server side

I've been working on implementing SSR with Next.js. In my code, I'm fetching JSON data and using them as initial props. Everything works fine in development mode, but when I deploy to the server, fetching only works on the client-side (when navi ...

Please ensure the subscription has completed before proceeding with the loop

I am currently working on an Angular application that retrieves data from an API and uses one of its parameters from a looped array. The issue I'm facing is that the data is pushed in a random order due to the continuous looping without waiting for th ...

Modify the useRef value prior to the HTML rendering (React functional component)

Hello everyone, I am attempting to update the value of useRef before the HTML is rendered. I have tried using useEffect for this purpose, but it runs after the HTML is ready, making it unsuitable for my needs. What I want to achieve is resetting the value ...

Gather information from various mongodb collections and consolidate them into a single array using Javascript

Is there a way to retrieve the most recent item from multiple collections and store them in an array based on the collection name and newest item? How can I accomplish this either sequentially or asynchronously? let dat = ["test", "test2"]; ...

I am confused by the combined output of the Array method and join function in JavaScript

In my JavaScript code, I declared the myArr variable in the following way: var myArr= Array(3); Upon logging the value of myArr, I received the output: [undefined × 3] Next, I utilized the JavaScript join function with the code snippet: myArr.join(&a ...

The external function in HTML Form's onsubmit attribute is failing to execute

My HTML Form has an onsubmit event that should call a validate() function. Everything works fine when the validate() function is inside a script tag at the end of the body tag. But if the validate() function is in an external JavaScript file, like in thi ...

What is the best way to access a component's value from a different component in Vue script?

I have two Vue components in my PHP file: "application" and "vn" component. I am trying to fetch {{obj.vacancies_left}} from the "vn" component and use it in the "application" component. However, I keep getting an undefined variable error. I attempted to r ...

Encountering an issue where rendering a component named Exercise within the ExerciseList component is not allowed

The ExerciseList component is designed to display all the exercises that can be edited or deleted from the list. It returns the Exercise Component or function for this purpose. If anyone could take a look and help identify any mistakes in my code, it would ...

The role of callback functions in TypeScript

As I embark on my journey with Angular 2 and TypeScript, one concept that has me a bit puzzled is how to implement callback functions. I understand that this might be a basic question, but when I look at this typical JavaScript code: someOnject.doSomethin ...

The Datatable feature is malfunctioning, unable to function properly with Javascript and JQuery

As a novice in the world of jquery/javascript, I find myself struggling with what may seem like an obvious issue. Despite following tutorials closely (the code for the problematic section can be found at jsfiddle.net/wqbd6qeL), I am unable to get it to wor ...

The variable in Vue.js is failing to update, resulting in a "variable is not defined" error

I've been attempting to display the updated value of the totalQuestions variable in the HTML, but I keep encountering the following error. Can someone point out where I went wrong? HTML <label><span class="red-text">Question No: </spa ...

What is the best way to access data from a local JSON file in Gatsby when using TypeScript and GraphQL?

I'm updating my former gatsby site using TypeScript. I encountered an issue while trying to retrieve data from a local JSON file: There appears to be an error in your GraphQL query: Cannot find field "allNavigationLinksJson" on type "Q ...

Error 404 in Angular HTTP Request

I'm encountering a 404 error while attempting to send a post request, along with a 'possibly unhandled rejection' error. Given my limited experience with Angular, any advice would be greatly appreciated. I've gone through the documentat ...