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

The React element's value dropped by two instances instead of one

I'm encountering a perplexing issue! The challenge I'm facing involves updating a deeply nested value within an object. This value is a number, and my goal is to decrement it by one with each click. However, when I attempt to do so, the value de ...

Getting the most out of Nexmo with multiple websocket connections

I have integrated the code provided by Nexmo (shown below) into my server. However, I am facing an issue where if two callers ping my server, the binary data from the second caller also streams into the same websocket endpoint, resulting in two binary st ...

Is there a more efficient method for converting an array of objects?

Is there a more efficient way to change just one value in an array without iterating through every element? I've included the code below where I am trying to update the contact number for each user in an array. Although my current solution works, it ...

Generating an interactive Datepicker using Jquery

How can I design a dynamic date picker similar to the image provided below? I have attempted to create one, but I am looking for a more interactive date picker. Is there a way to achieve the design shown in the image? The current date picker does not meet ...

Error: Unable to access the lexical declaration 'useStyles' before it has been initialized in the React Collapse Component. This issue occurred while trying to fetch data using axios in the Material-

I am facing an issue while trying to display data fetched from the backend (array with objects) and hide a portion of it under a collapsible button using Material-UI in React. The code works perfectly when all lines are written within a single component ca ...

Angular - Ensure completion of a function call before continuing with the code execution

I'm currently working on developing a code snippet that checks for potential adverse drug reactions between two medications. Within my checkForClash() function, there is a call to getCollisionsList(), which is responsible for populating the interacti ...

Maintaining the dropdown in the open position after choosing a dropdown item

The dropdown menu in use is from a bootstrap framework. See the code snippet below: <li id="changethis" class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown>LINK</a> <ul class="dropdown-menu"> <li id ...

Exploring the concept of multi-dimensional arrays within PHP

Can someone please help me create a multi-dimensional array with two variables? This is what I have tried so far: $_SESSION['name'][] = $row_subject['name']; $_SESSION['history'][]= $_SERVER['REQUEST_URI']; I am ...

Setting line chart data for Chart.js

Can you help me troubleshoot an issue I'm facing with creating a dataset for a line chart in Chart.js? Despite having an array of objects, the dataset isn't rendering correctly and I end up with two line charts instead of one. What could be causi ...

In MUI v5 React, the scroll bar vanishes from view when the drawer is open

Currently, I am working on developing a responsive drawer in React using mui v5. In the set-up, the minimum width of the drawer is defined as 600px when it expands to full width. However, an issue arises when the screen exceeds 600px - at this point, the d ...

Adjusting the overflow of a parent div based on the position of the div within it by scrolling

I'm trying to create a page with 3 different sections: <div class="container" id="main-container"> <div class="section" id="profile"> Hello World </div> <div class="section" id="projects"> Hello World 2 ...

Using Angular's ElementRef to set focus on an ion-textarea: "The 'setFocus' property is not found on the 'ElementRef' type."

After developing a textarea component that automatically focuses itself when created using the ngAfterViewInit() method, everything seemed to be working perfectly as expected. ngAfterViewInit() { if(this.text.length===0){ this.theinput.setFocus(); ...

What is the most efficient way to update a large batch of documents in MongoDB?

I need to efficiently update a large number of documents (> 100,000). Initially, I attempted to do this on the JS level by writing scripts that fetch _ids first and then loop through them to invoke updates by _id (full docs or $set patches). However, ...

Retrieve data by sorting based on the count column in a joined table with Sequelize

I've been struggling to make this work for some time and was hoping for some guidance. OBJECTIVE: I'm attempting to sort the posts by the number of likes they currently have. CURRENT: const posts = await db.post.findAll({ include: [ db.user ...

Steps to redirect to a webpage by clicking on an image without relying on anchor tags

Is it possible to redirect to a new webpage without using an anchor tag when someone clicks on an image? Below is my code for the image. <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/368px-Google_2015_l ...

Learn how to implement drag-and-drop functionality in React by making a component

I am currently experimenting with dragging a component using the react-dnd library. I wanted to replicate functionality similar to this example, specifically only focusing on dragging at the moment. In my application, I have imported and utilized the rea ...

What is the process for attaching the stack when initializing and throwing errors separately in JavaScript?

In all the documentation I've read, it consistently advises to both throw and initialize errors on the same line. For example: throw new Error("My error"); But what if you were to first initialize the error and then throw it on separate lines? For ...

We could not find the requested command: nodejs-backend

As part of my latest project, I wanted to create a custom package that could streamline the initial setup process by using the npx command. Previously, I had success with a similar package created with node.js and inquirer. When running the following comma ...

Utilize the angularJS filter to emphasize the search text within the search results

I have a search box that filters results displayed on the screen. I am using a filter called 'startWith' for this purpose. Now, I need to implement a feature where the search text is highlighted among the search results in angularJS. For example ...

How can I prevent the same JavaScript from loading twice in PHP, JavaScript, and HTML when using `<script>'?

Is there a PHP equivalent of require_once or include_once for JavaScript within the <script> tag? While I understand that <script> is part of HTML, I'm curious if such functionality exists in either PHP or HTML. I am looking to avoid load ...