A simple method in JavaScript/TypeScript for converting abbreviations of strings into user-friendly versions for display

Let's say I am receiving data from my backend which can be one of the following:

A,
B,
C,
D

Although there are actually 20 letters that could be received, and I always know it will be one of these specific letters. For example, I would like to map A to display as Alfa, and B should display as Beta. Is there a more efficient way to do this without creating a large switch statement?

I attempted using a constant like this:

export const Test = {
  SWE: 'Sweden',
  DK: 'Denmark'
}

And then trying to access it using:

Test[countrycode]

However, this causes an error stating

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ SWE: string; DK: string;

The reason quotes are missing around the keys is due to prettier formatting requirements.

Answer №1

Below are the necessary steps to resolve this issue.

  1. Create an interface specifically for the mapping variable to avoid encountering the Element is implicitly any... error in TypeScript
  2. Specify the type after your variable using a colon (:)
interface CountryMapping = {
   [key: string]: string  // This means that as long as the key is a string, it is valid for the key. Therefore, there's no need to manually specify every country code within the interface
}

export const countries: CountryMapping = {
  "SWE": "Sweden",
  "DK": "Denmark", 
  ...
}

// Example of how to use this mapping
const response = // Data received from the backend, where 'response' represents the letter

console.log(countries[response])

Answer №2

To retrieve specific values, all you need to do is create a mapping of the values you want and then loop through to get those desired values.

const mapValues = {
  'x': 'X-ray',
  'y': 'Yogurt',
  'z': 'Zebra'
}

const inputValues = ['x', 'y', 'v', 'z']

const mappedResults = inputValues.map(value => mapValues[value] || value);

console.log(mappedResults);

Answer №3

//let characterFromDatabase = "A";
let letterMap = {"A":"Alfa", "B": "Beta"};
return letterMap[characterFromDatabase] || characterFromDatabase;

//improved for case insensitivity
let letterMap = {"a":"Alfa", "b": "Beta"};
return letterMap[characterFromDatabase.toLowerCase()] || characterFromDatabase;

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

Ways to showcase Material-UI Grid components without using cards

I initially used Material-UI grid items for spacing adjustments, but now they are displaying as cards. I would prefer them to be invisible like before, but the documentation doesn't provide a solution for this issue. Any assistance would be greatly ap ...

Choose JSON information and modify it utilizing NODE.js with identical data

Feeling stuck.. I have a JSON file with some data and I need to manipulate it. Take a look at my JSON structure: [{ "method": "GET", "path": "/", "aliases": "", "name": "rootPath", "handler": "generatedApps/avion01/actions.HomeHandler" }, { "method": "GET ...

Wrapper around union function in TypeScript with generics

I'm struggling to find a solution for typing a wrapper function. My goal is to enhance a form control's onChange callback by adding a console.log. Can someone please point out what I might be overlooking? interface TextInput { type: 'Tex ...

Is it possible to use ref in React to reference various elements based on specific actions?

I'm having trouble targeting the clicked button using a ref as I always get the second one. Any ideas on how to solve this issue? Also, if I have a native select element with two optgroups, is it possible to determine from which optgroup the selection ...

It appears that the home page of next.js is not appearing properly in the Storybook

Currently, I am in the process of setting up my next home page in storybooks for the first time. Following a tutorial, I successfully created my next-app and initialized storybooks. Now, I am stuck at importing my homepage into storybooks. To achieve this, ...

Switching between Custom tooltips and default tooltips in Chart.js and Angular

I need to show a tooltip based on certain conditions options: { tooltips: if (tooltipCondition === true) { { mode: 'index', position: 'nearest' } } else { { enabled: false, custom: function (tooltipMo ...

The integration of Angular and Node API within the IISNode directory structure is experiencing functionality issues

Read more about the question I have successfully set up my Node API and Angular component with IISnode. However, when accessing the application from the IIS server, I noticed that they are showing in different directories (see image below). Additionally, I ...

Tips for arranging information in ng-repeat using nested objects within JSON data on AngularJS

Looking to display an array of object properties in an Angular view. Here is the object: $scope._Json = { "foo": { "ItemDimension1": { "Item": "item1", "ItemIndex": 1, "SelectedItems": [{ "C ...

Is there a way to switch the eventHandler assigned to a particular input element dynamically?

I am facing a dilemma with my child component, which dynamically generates input fields within a parent component. <app-xxx *ngFor="let el of fieldsElements" [ngModel]="fieldsElements[el.name]" ... ... (keydown)="my ...

You need to provide 1 type argument(s) for the Generic type ModuleWithProviders<T> in Angular 10 Swagger Codegen

Currently, I am generating Codegen proxies using . Upon implementing this in Angular 10, I encountered the following error. How can this issue be resolved? The error message reads: 'Generic type 'ModuleWithProviders' requires 1 type argume ...

Preventing Event Loop Blocking in Node.js: The Key to Streamlining Performance

I am currently working on developing two APIs using Express.js. The tasks for both APIs are quite straightforward. The first API involves running a for loop from 1 to 3,000,000, while the second API simply prints a string in the console. All the necessary ...

Include additional data in the FormData object before sending it over AJAX requests

Currently, I am utilizing AJAX to store some data. The primary concern I have is figuring out how to incorporate additional information into the FormData object along with what I already have. Below is the function that I'm using. Could you assist me ...

Chrome's rendering of CSS flex display shows variations with identical flex items

I am facing an issue with my flex items where some of them are displaying incorrectly in Chrome but fine in Firefox. The problem seems to be with the margin-right of the rectangle span within each flex item, along with the scaling of the text span due to f ...

How do I select the first element with class "cell" in D3, similar to jQuery's $(".cell:first")?

I have attempted this: d3.select(".cell:first") d3.selectAll(".cell").filter(":first") d3.selectAll(".cell").select(":first") but unfortunately, none of these methods are effective. ...

Express encountered an unexpected error when attempting to navigate to the client directory

I am attempting to send the index.html file from my client directory, located at the same level as my server directory. However, I am encountering the following error: TypeError: undefined is not a function at Object.handle (/myapp/server/routes/routes.js ...

What could be the reason for the inability to install Angular JS 2?

Setting up Angular 2 for experimentation on my VPS has been quite a challenge. The initial steps can be found here. Upon trying the first command: $ npm install -g tsd@^0.6.0 I encountered success. However, the second step led to an error: tsd install ...

Utilizing key values to access an array and generate a list of items in React.js

This marks my initiation on Stack Overflow, and I extend an apology in advance for any lack of clarity in my explanation due to unfamiliarity with the platform. My current task involves creating a resume with a dynamic worklist feature on my website. The ...

Placing a new item following each occurrence of 'X' in React components

Currently, I am working with a React component that uses Bootstrap's col col-md-4 styles to render a list of items in three columns. However, I am facing an issue where I need to add a clearfix div after every third element to ensure proper display of ...

A nifty little JavaScript tool

Recently, I created a bookmarklet that opens a new window with a specified URL and passes variables to a PHP script using the GET method. However, I now require it to load the same PHP script and pass the same variables but within a div element this time. ...

Choose an XPath selector that targets a list item within a specific div element

Currently, I am using selenium to conduct testing on a website. I have employed an XPath selector in order to locate a specific item within the HTML structure: <div id="boundlist-1051" class="x-boundlist list_cfg_cls x-boundlist-floating x-layer x-boun ...