A more effective approach than relying on an abundance of else if statements

I need to improve my Javascript code that handles different text options:

var personUrls = {
'amy': 'http://www.mydomain.com/amylikescats.html',
'dave': 'http://www.mydomain.com/daveshome.html',
'steve': 'http://www.mydomain.com/steve2.html',
'jake': 'http://www.mydomain.com/jakeeatstofu.html'
};

var url = personUrls[text] || 'http://www.mydomain.com/noone.html';

Do you have any suggestions for a more efficient approach?

Answer №1

Utilize an object as a mapping tool:

var map = {
    "amy": 'http://www.mydomain.com/amylikescats.html',
    "dave": 'http://www.mydomain.com/daveshome.html',
    // etc
};

var text = "whatever";
var url = map[text] === undefined ? 'http://www.mydomain.com/noone.html' : map[text];

By using this method, you can minimize repetitive code. However, if you require additional functionality beyond just setting url, consider using a switch statement.

Answer №2

Switch it up!

let website = 'http://www.mydomain.com/noone.html';
switch(selection) {
  case 'amy': website = 'http://www.mydomain.com/amylikescats.html';
  break;
  case 'dave': website = 'http://www.mydomain.com/daveshome.html';
  break;
  case 'steve': website = 'http://www.mydomain.com/steve2.html';
  break;
  case 'jake': website = 'http://www.mydomain.com/jakeeatstofu.html';
  break;
}

By initializing the website variable before the switch statement, a default clause is rendered unnecessary.

If needed, you can include this:

default: website = 'http://www.mydomain.com/noone.html';
break;

Answer №3

Key-Value pair container:

const info = {
  sarah: 'http://www.mywebsite.com/sarahsblog.html',
  mike: 'http://www.mywebsite.com/mikeshobby.html',
  // etc... 
}

How to utilize:

const link = info[text];

If the item is not found in the array, the else scenario can be handled by checking for its non-existence, elaborated below:

let link = '';
if(!(text in info)){
    link = 'http://www.mywebsite.com/mikeshobby.html';
}
else{
    link = info[text];
}

Answer №4

To simplify the process, store the distinct elements in a dictionary and proceed accordingly:

const uniqueElements = {
    amy: "amylovesdogs",
    dave: "davescats",
    steve: "steve3",
    jake: "jakeplaysguitar"
};
let link = uniqueElements[text];
if (!link) {
    link = 'http://www.mywebsite.com/noone.html';
} else {
    link = 'http://www.mywebsite.com/' + link + '.html';
}

Answer №5

To efficiently manage different URLs for various text values, consider utilizing an object to store these mappings. When assigning a value to the url variable, you can use the logical OR (||) operator to set a fallback URL if needed.

var urlsForText = {
      'sarah': 'http://www.mywebsite.com/sarahsjourney.html',
     'mike': 'http://www.mywebsite.com/mikesadventures.html',
     'lisa': 'http://www.mywebsite.com/lisafavorites.html',
     'john': 'http://www.mywebsite.com/johnsfamily.html'
};

var url = urlsForText[text] || 'http://www.mywebsite.com/default.html';

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

Issue with Vuex not functioning properly in Nuxt.js

I'm facing an issue with setting the state in Vuex on my Nuxt.js App. It seems to not be working correctly. So, here is how I am trying to set the state using the fetch method: fetch({app, store, route}) { app.$axios.$get(`apps/${route.params ...

Generate a separate div in an HTML file for each item listed in a JSON document

I have a JSON file structured like this: { "text": "HelloWorld", "id&quo;t: "1", }, { "text": "HelloMoon", "id": "2", } Now, I want to generate a <div> in my HTML for ...

Is there a way to convert the items in the products variable into the more comprehensive detailedProducts?

New to JS, looking for guidance on transforming the products variable into detailedProducts in JavaScript const products = [ { title: 'Yellow Pail', submitterAvatarUrl: 'images/avatars/daniel.jpg', productImageUrl: 'images ...

React is having trouble resolving the path required

Having an issue with the tracking-js library in my project. I'm using React and despite checking my package.json and confirming that the module is installed, I keep receiving errors indicating that the module cannot be found. This is how I am attempti ...

The color scheme detection feature for matching media is malfunctioning on Safari

As I strive to incorporate a Dark Mode feature based on the user's system preferences, I utilize the @media query prefers-color-scheme: dark. While this approach is effective, I also find it necessary to conduct additional checks using JavaScript. de ...

What is the best way to reference a component from another component in a React application?

I've been utilizing the react-notification-system library in my project, and here's a snippet of how I've incorporated it into my code. import React from 'react'; import Notification from 'react-notification-system'; cl ...

Enable divs to be interactively chosen

I have created two selectable divs that function like buttons. By using the left and right arrow keys, I am able to select one of the divs with this code: document.addEventListener("keydown", keyDownDocument, false); function keyDownDocument(e) { var k ...

Issues encountered while attempting to update data in angular2-datatable

Once the datatable has been rendered, I am facing an issue where I cannot update the data. I'm utilizing angular2-datatable. In my appcomponent.html file: If I try to update 'data2' in my appcomponent.ts file as shown below: this.httpserv ...

Using ThreeJS/WebGL to Send Functions to Shaders

I have created a custom noise function that accepts a 3D coordinate (x, y, z) and returns a noise value between 0 and 1. I am interested in incorporating this function into my vertex shader to animate vertex positions. Can I access this external function f ...

Counting JSON Models in SAP UI5

I am encountering a particular issue. Please forgive my imperfect English. My goal is to read a JSON file and count the number of persons listed within it. I want this result to be stored in a variable that is linked to the TileContainer. This way, whenev ...

AngularJS - sorting JSON data based on key values

I am working with a JSON data set that I need to filter based on the selected option value. The select input is bound to an ng-model, but for some reason, the filter isn't functioning properly. Can anyone spot what mistake I might be making? This is ...

What is the best way to generate an empty object that mimics the structure of an object within an array of objects in AngularJS

I am facing a scenario where I have an array of objects structured like this: $scope.users = [ { ID: "1", Name: "Hege", Username: "Pege", Password: "hp", }, { ID: "2", Name: "Peter", User ...

Refresh Form Following Submission

When using a react form that triggers a graphql mutation upon button click, the text entered in the form fields remains even after the mutation has been executed. This necessitates manual deletion of text for subsequent mutations to be run. Is there a way ...

Having trouble with my Express.js logout route not redirecting, how can I troubleshoot and resolve it?

The issue with the logout route not working persists even when attempting to use another route, as it fails to render or redirect to that specific route. However, the console.log("am clicked"); function works perfectly fine. const express = require('e ...

Display the date string in Material-UI TableCell格式

I have a TableCell component in Material-UI that displays dates in the format 2019-03-25T19:09:21Z: <TableCell align="left">{item.created_at}</TableCell> I want to change this to a more user-friendly format showing only the date as either 25/ ...

What causes the Invariant Violation: Invariant Violation: Maximum update depth exceeded error to occur when using setState()?

Looking for some help with this component: // here are the necessary imports export default class TabViewExample extends Component { state = { index: 0, routes: [ { key: 'first', title: 'Drop-Off', selected: true }, ...

Transferring data between functional components in ReactJS and dealing with the output of [object Object] or undefined

I'm struggling with passing a prop in functional components that are both located in the same .js file. I previously attempted to seek help for this issue, but unfortunately, it wasn't productive. My goal is to extract the member_id from the GET ...

Organize the JSON data in a particular manner

I have a set of JSON data that looks like this: [ { "name": "Event 1", "sponsors": [ { "name": "Walmart", "location": "Seattle" }, { "name": "Target", "location": "Portland" }, { ...

Guide to implementing dynamic conditional rendering in Vue.js loops (utilizing v-if within v-for)

I am currently working on a table component in a .vue file where I want to display icons based on the direction of the order clicked. For example: <th v-for="(column, index) in columns" :key="index" @click="sort( index )"> <span& ...

How can I implement a single Ajax call to load content from various pages and display it

This code facilitates an ajax call to dynamically change the content of a div in the main page without requiring a full page reload: function ajaxcall() { $.ajax({ type: "POST", url: "/create.php", success: function( returnedDa ...