Ways to showcase corresponding information for an item contained within an array?

I'm working with a function that is designed to retrieve specific descriptions for objects nested within an array. The purpose of the function (findSettings()) is to take in an array (systemSettings) and a key (tab12) as arguments, then use a switch statement to match the key and provide its corresponding description.

In simpler terms, if the argument passed to the function is 'tab12', it should output 'Description for tab12'.

I initially attempted to locate a matching object using the find method, which was successful. However, when I tried implementing the switch statement, I encountered an error message stating 'Object is possibly undefined'.

const systemSettings = [
  {key: 'tab1', value: 'Main Tab'}, 
  {key: 'tab12', value: 'Tab 12'}, 
  {key: 'tab13', value: 'Tab 13'}, 
  {key: 'tab4', value: 'Tab 4'}
]

type sampObj = {
  key: string;
  value: string;
}

let info: string = '';

function findSetting(arr: sampObj[], settingKey: string) {

  const selectedObjs = arr.find(obj => obj.key === settingKey);

  switch(selectedObjs.key) {
    case 'tab1':
      info += 'Description for tab1';
      break;
    case 'tab12':
      info += 'Description for tab12';
      break;
    case 'tab13':
      info += 'Description for tab13';
      break;
    case 'tab4':
      info += 'Description for tab4';
      break;
    default: 
      info += 'No description available'
  }

}

findSetting(systemSettings, 'tab12')

Answer №1

To simplify this solution, consider using a Map to store descriptions with keys. TypeScript provides a convenient Utility Type called Record for ensuring type safety. This way, you don't need to pass an array in the findSetting function.

  systemSettingsDescriptions: Record<string, string> = {
    tab1: "Description for tab1",
    tab2: "Description for tab2",
    tab3: "Description for tab3"
  };

  systemSettings: sampObj [] = [
    { key: "tab1", value: "Main Tab" },
    { key: "tab12", value: "Tab 12" },
    { key: "tab13", value: "Tab 13" },
    { key: "tab4", value: "Tab 4" }
  ];

  function findSetting(settingKey: string): string {
    return this.systemSettingsDescriptions[settingKey] || "No description available";
  }

Answer №2

Make sure to verify if the object exists in the array using <code>const selectedObjs = arr.find(obj => obj.key === settingKey);
. It may return undefined if no object with the specified key is found.

Prior to running your switch statement, it's recommended to check if the object is not undefined:

if(selectedObjs) {
   switch(selectedObjs.key) {
       case 'tab1':
          info += 'Description for tab1';
          break;
        case 'tab12':
          info += 'Description for tab12';
          break;
        case 'tab13':
          info += 'Description for tab13';
          break;
        case 'tab4':
          info += 'Description for tab4';
          break;
        default: 
          info += 'No description available'
  }
}
else {
   // Handle scenario when settingKey is invalid
}

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

When attempting to insert a date into a MySQL database using React.js, I encountered an issue with the date format

Hey everyone, I have set the input date to dd/mm/yyyy format using moment(donors.donateDate).format('DD-MM-YYYY'). However, when I click the submit button, an error is displayed in the console stating: The specified value "23-03-2022" ...

If the first dropdown menu has a sub-element, then the user should be able to select the same value in the second dropdown menu using jQuery

To trigger an alert, two HTML select option dropdowns must both have the value DIP EDU. My current code successfully accomplishes this, but there is a scenario where some options in the first dropdown may contain sub-elements. For example, selecting MBA wi ...

React Typescript does not support the use of React-Router

I'm currently working on a React app that utilizes Typescript. The React version is set to "react": "^16.9.0", and the React-Router version is "react-router-dom": "^5.1.2". Within my App.tsx file, the structure looks like this: const App: React.FC ...

What is the importance of including "declare var angular" while working with Typescript and AngularJS?

I've been working on an AngularJS 1.7 application that's coded entirely in TypeScript, and there's always been one thing bothering me. Within my app.module.ts file, I have this piece of code that doesn't sit right with me: declare va ...

What is the best method for transforming an object into an interface without prior knowledge of the keys

I am looking for a solution to convert a JSON into a TypeScript object. Here is an example of the JSON data: { "key1": { "a": "b" }, "key2": { "a": "c" } } The keys key1 and key2 a ...

Exploring the benefits of using getServerSideProps with NextJS and Typescript for

Dear community, I am facing a challenge with integrating NextJS Layout and Typescript. Although everything seems to be working fine, I can't seem to get rid of the squiggly line under the props when passing them from getServerSideProps. The prop {som ...

Using Typescript for testing React components: successfully passing an array of objects as props

My current approach involves passing an array of objects to mock component data for testing: const mockPackage = { id: '1232-1234-12321-12321', name: 'Mock Package', price: 8.32, description: 'Mock description', glo ...

"Enhance User Experience with Material UI Autocomplete feature that allows for multiple

I am encountering an issue with a material ui auto component that I am currently working on. The component's code looks like this: <Autocomplete multiple options={props.cats} defaultValue={editRequest? ...

Ensure that the method is passed a negative number -1 instead of the literal number 1 from an HTML error

This is an example of my HTML code: <button (mousedown)="onMouseDown($event, -1)"></button> Here is the TypeScript code for handling the mouse down event: onMouseDown(e: MouseEvent, direction: 1|-1) { this.compute.emit(direction); ...

An error was thrown due to an unexpected end of JSON input while fetching from localhost

After running the code snippet provided, I encountered an Uncaught SyntaxError: Unexpected end of JSON input. As a beginner in coding, any guidance or assistance would be greatly appreciated. Thank you. fetch('http://localhost:3000/add-user', { ...

What is the best way to apply DateRange filtering in a Kendo Ui Grid?

Currently I am working with the Kendo Ui Grid and attempting to implement filtering by DateRange. Here is a snippet of my current code: HTML: <kendo-grid-column field="createdate" title="Creation Date" width="150"> <ng-template kendoGridFilterC ...

Any ideas on how to format a date for jQuery Datepicker?

Currently, I have implemented two different datepickers on my website, but I am interested in switching to jQuery's Datepicker for a more unified solution. Here is the current format that I am sending to our backend API: However, I would prefer to i ...

The Vue component fails to respond to updates in plugin data

I am currently working on implementing a feature where a component reacts to data changes in a custom Vue plugin. To achieve this, the plugin creates a new instance of a Vue object in its constructor: this._vm = new Vue({ data: { obj: null, stat ...

Instructions for adding a select dropdown feature in Angular 6 that includes a search filter. Additionally, tips on how to filter objects by their name property

I need to add an auto-complete feature in my Angular 6 app where the data is displayed as objects in a dropdown and filtered as we type. **template.html** <mat-form-field > <input matInput [matAutocomplete]="auto" [formControl]="customerFi ...

Unable to execute the new firebase on node server

I'm currently watching this google talk. However, I am facing an issue trying to create a firebase object. Following my package.json file, I initiated with: npm install firebase --save Then proceeded with the following steps: let Firebase = requir ...

Utilizing use-immer and promises to effectively handle an API route mapping system

In the process of tackling the issue of double hook calls in Next.js dev mode, I've encountered a challenge with server API calls that cannot handle duplicates. To address this, I opted for fix #4 outlined in the following article, where I decided to ...

Firefox throwing an error with jQuery URL Get requests

Could someone help me understand why my JavaScript function is triggering the error function instead of the success function in Firefox on Ubuntu? $(document).ready(function() { console.log( "Begin" ); $.ajax({ type: "GET", dataType: "ht ...

What could be the reason for the sudden failure of my jQuery + AJAX functionality?

As a novice in JavaScript/jQuery/AJAX, I have a suspicion that the issue lies in some typo that I may have overlooked. Everything was working perfectly, but when I made some edits, the hide() + show() methods stopped functioning (I tested it on both Firefo ...

Troubleshooting the issue with mocking API and creating a regular expression to match the dynamic part of a URL

I am struggling to create a mock for an API that includes dynamic parts in the URL. I attempted to use a regular expression, but it is not functioning as expected. The URL I am trying to mock is: https://example.com/programs/2fcce6e3-07ec-49a9-9146-fb84fb ...

Unexplained disappearance of div element in Vue Router's Navbar

I have been working on integrating a Vue Router into my navbar and everything seemed to be going well. You can check out the code here. The navigation menu I created works perfectly, allowing users to navigate between the home template and about template w ...