Is there a way to condense this JavaScript if statement further? (if 1, if 2)

Currently, I am in the process of developing a website that utilizes data extracted from an API. My goal is to implement an if-else statement that dynamically changes the HTML output based on whether the result is 0, 1, 2, or 4. Is there a way to condense this logic into a single statement instead of having four separate blocks of code?


if(data.results.indexOf(element) >= 0 && data.results.indexOf(element) <= 3){
    let dynamicResult = document.getElementById(`result${data.results.indexOf(element)}`);
    dynamicResult.style.display = "block";
    dynamicResult.innerHTML = `${element.original_title}`;
}

Answer №1

To organize an array efficiently, you may use indexing:

const item = [result0, result1, result2, result3][data.results.indexOf(element)];
item.style.display = "block";
item.innerHTML = element.original_title;

Answer №2

Some might not agree with me, but an alternative approach could be:

let result = eval(`result${data.results.indexOf(element)}`);
result.style.display = "block"
result.innerHTML = `${element.original_title}`

Nevertheless, as mentioned, it is advisable to store all elements in a numerical array rather than relying on guessing their variable names.

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

Is it necessary to implement the useCallback hook along with React.memo for rendering optimization in React components?

As I delved into understanding how useCallback and useMemo function in React to optimize app performance, I decided to create a simple app for experimentation. What I observed was that the callback function (OnBlurHandler) passed to my child component trig ...

Collapse component in Ant Design UI renders without bullets when using the ul tag

When I insert children tags like this in antd collapse <Collapse accordion expandIconPosition="end" items=[{ key: '1', label: '123', children: <ul><li>1</li><li>2</li><li>3</li&g ...

Could JSON.parse have a glitch in Firefox?

While using Firefox 23.0.1, I encountered the following code snippet: var foo = '{ "success": false, "errtype": "barf", "message": "my message\n"}'; var what = JSON.parse(foo); console.log(what); Upon running this code in the Firebug J ...

Tips for executing multiple function calls within a single React component

Struggling to retrieve information from two separate API calls within the same React component. The issue seems to be with accessing the similar data in the code provided. function Info() { let params = useParams(); const [details, setDetails] = useSt ...

Struggling to extract text from within a <p> tag on an Ionic 1 app page on iOS

After developing an ionic-1 application for iOS and Android devices, I encountered an issue with displaying mobile numbers in one of the views. The numbers are contained within <p> tags. While users can click and hold on a number to copy it on Andr ...

Implementing a 10-second alert display in selenium

Task at Hand: I need to display the alert on my page for a few seconds to allow reading. Is there any function in Selenium Web-driver that can help with this? I am new to automation and have been learning about explicit waits. I tried using explicit wait ...

Connecting Formik with the react-phone-number-input library: A step-by-step guide

I am currently working on developing a form using Formik, Material UI, and the React-phone-number-input library for phone number formatting. I have encountered an issue where the formatted phone number is not being inserted into the Formik state, causing F ...

What steps are necessary to create an npm package utilizing three.js without any dependencies?

I have a challenge - I am trying to create an npm package that generates procedural objects for three.js. The issue I'm facing is how to properly include three.js in my code. I attempted to establish a dependency and use something like const THREE = r ...

Organizing files on a website for collaborative projects involving multiple team members

I am currently constructing a website with the following specifications: Pages are being loaded inline via AJAX. CSS, HTML, JavaScript, and PHP are all separated to facilitate collaboration on projects. While working on creating a dynamic <select> ...

Vue 3 TypeScript not updating property following API request

Working with an API on Node.js and calling it with Vue has presented a challenge for me. After making the call and receiving the results, I attempt to parse them and push them onto a property in the class so they can be passed down to a component. However, ...

Guide to successfully setting up a Json server and ReactJS to run simultaneously on the same port

Currently, I am facing an issue while attempting to run my React application with a JSON server as the backend API. The problem arises when trying to run them on different ports due to a CORS error. I am currently seeking advice and looking for a solutio ...

Emphasizing the content of the text file with the inclusion of span tags

I am relatively new to working with angular js and javascript. I have a document or text file that looks something like this: Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dumm ...

Utilizing a try/catch block for validating a JSON file is ineffective

I'm attempting to verify if a received string is JSON and I experimented with the code below: try { JSON.parse(-10); // Also tried with "-10" }catch(e) { console.log('inside catch'); } Surprisingly, the code never enters the catch ...

Showcasing a variety of scenarios where resources are being used across several canvases

I am currently working on a project using three.js to develop an interactive web application, but I have hit a roadblock: Within the design, there are numerous canvases enclosed in draggable divs on the page. Each canvas is meant to showcase a 3D object w ...

`npm run build` in Ubuntu does not detect any environment variables in process.env

Currently in the process of deploying a VueJS project. I have a file that contains API URLs where process.env is used. In production, if API_URL is defined, I can use localhost on my development server and switch to API_URL in production. const apiRoot = p ...

Retrieving and showing items based on the user's ID in MongoDB

I am attempting to retrieve and display all entries in the 'item' collection that belong to a specific user/userID from the user collection. item_controller.js: const Item = require('../models/item_schema') const getUserItems = (req, ...

Placing buttons on top of a video within a div container

I am facing a challenge with implementing custom controls on a video embedded in my webpage. I have tried setting a div to absolute position for the buttons, but they are not clickable. Is there a way to achieve this without using jQuery? I need the butto ...

How can I best fill the HTML using React?

After attempting to follow various React tutorials, I utilized an API to fetch my data. Unfortunately, the method I used doesn't seem to be very efficient and the code examples I found didn't work for me. I am feeling quite lost on how to proper ...

Hide a div element upon selecting an option from a dropdown menu

On iPhone 6plus and lower, I created a dropdown menu that opens when users click on "jobs" or "contact." However, after clicking on these options, the drop-down menu remains open. How can I make it hide automatically after a list item is clicked at this sp ...

When it comes to JavaScript, it considers the number 0 as equivalent

I am facing an issue with my spring endpoint that is returning an Enum named StatoPagamentoEnum: Java enum definition @JsonFormat(shape = JsonFormat.Shape.ARRAY) public enum StatoPagamentoEnum { DA_PAGARE(0), PARZIALMENTE_PAGATA(1), PAGATA(2 ...