Switch between active tabs (Typescript)

I am working with an array of tabs and here is the code snippet:

const navTabs: ITab[] = [
    { Name: allTab, Icon: 'gs-all', Selected: true },
    { Name: sources.corporateResources, Icon: 'gs-resources', Selected: false },
    { Name: sources.employee, Icon: 'gs-people', Selected: false },
    { Name: sources.services, Icon: 'gs-services', Selected: false },
    { Name: sources.information, Icon: 'gs-docs', Selected: false },
    { Name: sources.tableau, Icon: 'gs-tableau', Selected: false },
];

In the method to activate a tab, I change the currently selected tab from selected: true to false and then set the new tab to selected: true.

Here is the activating code:

public activateTab(name: TabName): void {
    this.activeTab = name;
    this.navTabs.find(x => x.Selected === true).Selected = false;
    this.navTabs.find(x => x.Name === name).Selected = true;
}

I'm wondering if there's a way to simplify this into a single operation. Is it possible?

this.navTabs.find(x => x.Selected === true).Selected = false;
this.navTabs.find(x => x.Name === name).Selected = true;

Answer №1

You can iterate through all of them using the forEach method and then assign the value of Selected based on a condition where you compare the name:

const menuItems = [
  { name: 'foo', icon: 'gs-all', selected: true },
  { name: 'foo', icon: 'gs-resources', selected: false },
  { name: 'foo', icon: 'gs-people', selected: false },
  { name: 'bar', icon: 'gs-services', selected: false },
  { name: 'foo', icon: 'gs-docs', selected: false },
  { name: 'foo', icon: 'gs-tableau', selected: false },
];

const nameToFind = 'bar';

menuItems.forEach(item => item.selected = (item.name === nameToFind));

console.log(menuItems);

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

What is the best method for modifying an array variable?

I am working with a variable array named data for my IGcombobox datasource. I need to update the array when I click on my #select element, but the current code is not changing the variable. Is there a way to achieve this without using PHP? <div id="c ...

What might be causing AngularJS to fail to display values when using TypeScript?

I have designed the layout for my introduction page in a file called introduction.html. <div ng-controller="IntroductionCtrl"> <h1>{{hello}}</h1> <h2>{{title}}</h2> </div> The controller responsible for handling th ...

Click on a link to navigate to a new page using the useNavigate hook in

I have successfully implemented navigation using the useNavigate hook, but I am wondering if there is a way to open the URL in a new tab instead of the current one. Is this achievable? Here's my code: import { useNavigate } from "react-router-do ...

Discovering the culprit causing a freeze on your page: Uncovering the tool or technique to identify the problematic

What is the best tool to identify resource-heavy or infinite loop JavaScript/jQuery scripts? I am currently experiencing issues with a specific template: When I open this page on Firefox 46.0.1, it freezes after a few minutes. I am having trouble pinpoin ...

Instruction Leads to Input Losing Focus

I have developed a custom directive for allowing only numbers in an input field: @Directive({ selector: 'input[numbersOnly]' }) export class NumbersOnlyDirective { constructor(private ref: ElementRef, private control: NgControl) { } @Hos ...

Tips on implementing pdf-lib in Angular?

I came across the pdf-lib library and am interested in incorporating it into my Angular project. However, I couldn't find any documentation on how to import it specifically for Angular. Can anyone assist me with the process of importing this library ( ...

Importing JSON data into JavaScript

For the past few hours, I've been attempting to load a JSON file into JavaScript to feed map coordinates to the Google Maps service. Unfortunately, my script is incomplete and I cannot obtain any results. Here's what I have so far: <script&g ...

Tips on preventing state sharing in Angular applications

Delving into the world of Angular has presented me with an intriguing issue. I've crafted a component dedicated to displaying a dialog, complete with its own template (HTML), CSS, and TypeScript files. Whenever a user clicks on an item within a list ...

Leveraging the power of javascript to include content before and after

I am looking to understand how I can insert an HTML element before and after certain elements. For example, let's say we have the following code in a real file: <ul class="abcd" id="abcd></ul> How can I display it like this using JavaScr ...

Delving into the World of ES6 Symbols

Throughout my experience with various programming languages, from C# to Lisp to Scala to Haskell, symbols have consistently behaved as singleton objects. This means that any two symbols with the same name are guaranteed to be identical. In Racket: (equal? ...

Clicking on the parent page prevents the hyperlink inside the iframe from working as expected

I am having an issue with a hyperlink inside an iframe. When I click on it in the parent page, it doesn't work. Here is how it is set up: iframe.html <h1>I'm inner page!</h1> <a id="shared" class="btn" href=&q ...

Error: cannot use .json data with `filter` method from WEBPACK_IMPORTED_MODULE_2__["filter"]

There seems to be an error occurring when attempting to retrieve data from a JSON file in the specific line of code selectedEmployee: employeeList.data.Table[0], An issue is arising with TypeError: _employeeList_json__WEBPACK_IMPORTED_MODULE_2__.filter ...

Is it possible to manipulate the response from a MySQL server using Node.js?

For example: The following response represents the original data { "todo_id": 2, "todo_item": "brush your teeth", "scheduled_time": "2020-03-22T07:14:29.000Z", "user_id": 1, "is_done": { "type": "Buffer" ...

Guide to incorporating external code in InversifyJS without direct control

I'm wondering if it's feasible to add classes that are not editable. Inversify seems to rely heavily on annotations and decorators, but I'm curious if there is an alternative method. ...

Guidance on editing list items individually using jQuery from separate input fields

Working with li presents some challenges for me. On my webpage, I have an input field that dynamically adds values to a list. However, the function to edit these values is not working properly. After editing an li element, it deletes all classes and span ...

Utilize Angular's ability to set values in line while clicking using an asynchronous function

I am facing a unique challenge where I need to assign a value to a variable inline using a click event that triggers an async function call. The scenario involves rendering a deeply nested and complex set of objects on the screen within an ng-template (e.g ...

Issue with IE11: the selected list is not displayed when using the <s:optiontransferselect> tag

When moving groups from left to right in the s:optiontransferselect for selectedGrps and unselectedGrps, the SelectedGroups list is showing as null on form submission in IE11. However, in Chrome and Mozilla, it functions correctly. Any advice would be grea ...

What is the best method for choosing elements when I already possess a DOM element?

When you have a variable that contains a DOM element and need to select related elements, you can easily achieve this by wrapping it in a jQuery object. var myDomElement = document.getElementById("foo"); $(myDomElement ).find("a"); It is common for peopl ...

Unraveling HTML elements within a string using MongoDB: A step-by-step guide

Currently, I am in the process of creating a blog from scratch as a way to enhance my skills. The posts' content is stored as a long string in MongoDB with some random HTML tags added for testing purposes. I am curious about the conventional method fo ...

What is an example scenario where Async Storage can be tested using Jest-expo?

To better understand the testing of Mock-async-storage for reactjs, I decided to replicate an example. If you have any suggestions on a different approach to testing, please feel free to share. I attempted to mimic a use case illustrated on this stack over ...