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 adjust the text size in jqGrid?

The current theme is ui-lightness. How can I adjust the font size within the grid? Your suggestions are appreciated. Many thanks. ...

I'm at a loss with this useState error, can't seem to figure

Could you please help me understand what is incorrect in this code snippet? import React, { useState } from 'react'; import UsrInput from '../component/UsrInput' import TodoItemList from '../component/TodoItemList' const ...

Angular version 7.2.1 encounters an ES6 class ReferenceError when attempting to access 'X' before it has been initialized

I have encountered an issue with my TypeScript class: export class Vehicule extends TrackableEntity { vehiculeId: number; constructor() { super(); return super.proxify(this); } } The target for my TypeScript in tsconfig.json is set to es6: ...

Only initiate the loading of the iframe within the div upon clicking a specific element

Is there a way to delay loading the content of a div until it's clicked, instead of having all data loaded at once when the page loads? I noticed that removing unnecessary divs made the page load much faster. How can I prevent all data from being loa ...

Use `$$state: {…}` within the request rather than the data

When attempting to send a request with data, I am only getting "f {$$state: {…}}" in the console. $scope.createTask = function () { var req = $http.post('api/insert', { title: $scope.newTitle, description: ...

Determine whether the elements in the master array match the elements in the child array

Checking for data presence in arrays: [ { "productDisplay": "ZXP 105", "productNumber": "WZDR 112" }, { "productDisplay": "ZXP 106", "productNumber": "WZDR 113" } ] ChildArray [{productDisplay:"ZXP 105", ...

Discovering the power of ng-change in an Angular typeahead search functionality

I am facing an issue with displaying the result list when searching for users on key press using customTemplate.js. The list is not showing up after the first key press. Below is the code I am using: <input type="text" placeholder="Search people here ...

Transmit an Array using Ajax and retrieve it on an ASP Classic page

I am facing a challenge where I need to pass an array using AJAX on an ASP page. After trying to send it as GET method and checking the data being received, I noticed that only the LAST record of the array is being processed by ASP. How can I successfu ...

Is there a way to identify the browser version that is being used?

I've been on the lookout for a specific code snippet that can help me identify whether the user visiting my website is using Firefox 3 or 4. Thus far, I have only come across code to determine the type of browser without indicating the version. Is th ...

Is there a one-liner to efficiently eliminate all instances of a specific sub-string from an array using the filter

In search of a solution to filter an array and eliminate all instances of substrings, similar to removing entire strings as shown below: const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"] x= x.filter(i ...

Moving object sideways in 100px intervals

I'm struggling to solve this issue. Currently, I have multiple div elements (each containing some content) that I need to drag and drop horizontally. However, I specifically want them to move in increments of 100px (meaning the left position should b ...

Can you explain the distinction between employing 'from' and 'of' in switchMap?

Here is my TypeScript code utilizing RxJS: function getParam(val:any):Observable<any> { return from(val).pipe(delay(1000)) } of(1,2,3,4).pipe( switchMap(val => getParam(val)) ).subscribe(val => console.log(val)); ...

How can I use jQuery to separate special characters from letters in a string?

I'm facing an issue with my code related to validation. There is a existing validation in place that restricts users from entering letters and special characters in a textfield. Now, I need to incorporate this validation into my code but I'm uns ...

"There is an issue with the payload size: request entity is too large. What is the solution for handling this in Nest

I am facing an issue where I need to send a request containing a large base64 string, approximately around 2 MB. However, the server keeps throwing an error message. How can I prevent this error from occurring: [Nest] 1666 - 11/01/2021, 1:50:58 PM ERRO ...

Check domains using Jquery, AJAX, and PHP

I'm currently developing a tool to check domain availability. Here is the PHP code I have so far: <?php $domain = $_GET["domname"]; function get_data($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch, CURLOPT_URL, $url); ...

Comparison Between React-Redux mapStateToProps and Inheriting Props from ParentsIn the

Excuse my lack of experience, but I am currently delving into the world of react-redux and trying to grasp the concepts as I progress. Situation: In my main component within a react-redux application, I have the following snippet at the end: function map ...

What is the best way to incorporate material-ui icons into my project?

I'm trying to incorporate an icon inside an IconButton, like so: <IconButton > <SearchIcon/> </IconButton> After adding @material-ui/icons to my package.json file and importing the necessary components: import IconButton from ...

Hide bootstrap card on smaller screens such as sm and md

Utilizing the Bootstrap 4.1 card component, I showcase categories within the right sidebar - check out a sample image of the card here: Card example image; When viewing on smaller screens, it's preferable to collapse this large card as shown in this ...

Navigating JSON Data in Groovy Using a Loop: A Handy Guide

Just starting out with Groovy and attempting to mock a service in SoapUI. The task at hand involves loading a text file containing JSON data, and then matching that data to a specific node. Here is what I have attempted so far: def inputFile = new File( ...

Ways to retrieve form information from a POST request

I received a POST request from my payment gateway with the following form data: Upon trying to fetch the data using the code snippet below, I encountered errors and gibberish content: this.http .post<any>('https://xyz.app/test', { ti ...