Steps for selectively targeting and updating a group of properties in a TypeScript class

Is there a way to consolidate this code into one function that can handle all the tasks below?

I'm adding more text here to meet the requirements and hoping for a solution. Thank you! TypeScript is an amazing language that differs slightly from JavaScript. I tried my own method to resolve the issue below, but kept getting 'undefined'. It's challenging to group, target, and change the values.


class foods {
    private apple: boolean;
    private banana: boolean;
    private guava: boolean;
    private passionfruit: boolean;
    private melon: boolean;
    private oranges: boolean;
    private porkchop: boolean;
    private steak: boolean;
    private chicken: boolean;

    toggleFruit(fruit: string) {
        for (let key in this) {
            if (this.hasOwnProperty(key)) {
                this[key] = false;
            }
        }
        this[fruit] = true;
    }

}


Answer №1

If you're looking to streamline your code, consolidating everything into a single function is a great approach. While there may be more innovative solutions out there, this method effectively centralizes all the logic within a toggle function.

apple: boolean;
banana: boolean;
guava: boolean;
passionfruit: boolean;
melon: boolean;
oranges: boolean;
porkchop: boolean;
steak: boolean;
chicken: boolean;

constructor(
) {
    this.apple = false;
    this.banana = false;
    this.guava = false;
    this.passionfruit = false;
    this.melon = false;
    this.oranges = false;
}

toggleFruit(fruitName: string) {
    (fruitName === 'apple' ? this.apple = true : this.apple = false);
    (fruitName === 'banana' ? this.banana = true : this.banana = false);
    (fruitName === 'guava' ? this.guava = true : this.guava = false);
    (fruitName === 'passionfruit' ? this.passionfruit = true : this.passionfruit = false);
    (fruitName === 'melon' ? this.melon = true : this.melon = false);
    (fruitName === 'oranges' ? this.oranges = true : this.oranges = false);
}

Answer №2

You have the option to create an Array of Objects containing two key-value pairs: name and status.

Here is an example:

   foodList = [
      { name: 'Apple', status: false },
      { name: 'Banana', status: false }
      ...
    ];

The name property represents the food item's name, while the status property indicates whether the food item is true or false.

Next, you can create a method that takes the food name as a parameter.

toogleFood(foodName: string) {
   this.foodList.map( food => {
      if (food.name === foodName) {
         food.status = true;
      }
   });
}

Answer №3

Give this a shot

class groceries {
    private selected: string[] = [];

    toggleCarrot() {
        this.toggleProduct('carrot');
    }

    toggleBroccoli() {
        this.toggleProduct('broccoli');
    }

    togglePineapple() {
        this.toggleProduct('pineapple');
    }

    toggleKiwi() {
        this.toggleProduct('kiwi');
    }

    toggleMango() {
        this.toggleProduct('mango');
    }

    togglePeach() {
        this.toggleProduct('peach');
    }

    private toggleProduct(name: string): void {
        if (this.selected.includes(name)) {
            this.selected = this.selected.filter((selectedName) => selectedName !== name);
        } else {
            this.selected.push(name);
        }
    }
}

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

404 Error message encountered across all routes in a Node TypeScript Azure Function App - Resource not located

I keep encountering a 404 Not Found error on all routes while requesting my API. I am struggling to correctly write the code. Here's an example of my code: host.json: { "version": "2.0", "extensions": { & ...

How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval(). Here's the snippet of my code: export class SmileyDirective { FillGraphValues() { console.log("The FillGraphValues function works as expect ...

Creating a TypeScript definition file to allow instantiation of a module

I'm encountering an issue with creating a declaration file for an existing module. When using JavaScript, the module is imported using the following syntax: var Library = require('thirdpartylibs'); var libInstance = new Library(); I have ...

What is the most effective way to share data among components in React?

I recently delved into learning about react and find myself puzzled on how to pass data between two components. Presently, I have set up 2 functions in the following manner: First, there's topbar.tsx which displays information for the top bar, inclu ...

Automatically select the unique item from the list with Angular Material AutoComplete

Our list of document numbers is completely unique, with no duplicates included. I am attempting to implement a feature in Angular Material that automatically selects the unique entry when it is copied and pasted. https://i.stack.imgur.com/70thi.png Curr ...

Tips for recognizing the click, such as determining which specific button was pressed

Currently, I am utilizing Angular 6. On the customer list page, there are three buttons - "NEW", "EDIT", and "VIEW" - all of which render to one component. As a result, it is crucial for me to determine which specific button has been clicked in order to ...

Choose an option from a selection and showcase it

I need to implement a modal that displays a list of different sounds for the user to choose from. Once they select a sound, it should be displayed on the main page. Here is the code snippet for the modal page: <ion-content text-center> <ion-ca ...

Angular2 and ES6 Promise in JavaScript - tackling the issue of undefined variables

I am working with an array of objects like the one shown below: let PAGES = [ new BasePage( 'home', 'test') ]; let pagesPromise = Promise.resolve(PAGES); My goal is to retrieve a BasePage object by calling the following met ...

The useState variable remains unchanged even after being updated in useEffect due to the event

Currently, I am facing an issue in updating a stateful variable cameraPosition using TypeScript, React, and Babylon.js. Below is the code snippet: const camera = scene?.cameras[0]; const prevPositionRef = useRef<Nullable<Vector3>>(null); ...

Struggling to determine data type in Typescript

My goal is to create an interface for my realm Database using TypeScript. Essentially, I have an automation bot and I want to monitor and track how users are utilizing it. To achieve this, I have designed specific schemas that will be integrated into an i ...

Implementing dynamic display of div based on dropdown selection in typescript

A solution is needed to display or hide specific div elements based on a dropdown selection using Typescript. Sample HTML file: <select class="browser-default custom-select"> <option selected>single</option> <option value="1"> ...

Encountering "Undefined error" while using @ViewChildren in Angular Typescript

In my application, I am facing an issue with a mat-table that displays data related to Groups. The table fetches more than 50 rows of group information from a data source, but initially only loads the first 14 rows until the user starts scrolling down. Alo ...

The NextAuth getServerSession function is functional when used with a POST API method, but it

Encountering an issue where getServerSession functions correctly on a POST route but not on a GET route. import { getServerSession } from "next-auth" import { authOptions } from "../../auth/[...nextauth]/route" import { NextResponse } f ...

Unable to utilize the "let" keyword in WebStorm

Currently, I am delving into learning typescript and attempting to create a simple 'let' statement. However, I encountered an error indicating the need to use ECMAScript 6 or later versions. The exact message from the typescript compiler states: ...

Tips for packaging a Node TypeScript/JavaScript library using Webpack

I am currently working on a Node project with the following setup: Written in Typescript Using Webpack and ts-loader for bundling Targeting Node.js +-proj/ +-src/ |-file1.ts |-file2.ts |-file3.ts |-... |-package.json |-webpack.confi ...

How to filter an array in Angular 4 without the need for creating a new array and then displaying the filtered results within the same

In my collection of students, I have their names paired with their academic outcomes. studentResults = [ {name: 'Adam', result : 'Passed'}, {name: 'Alan', result : 'Failed'}, {name : 'Sandy', result : &ap ...

Issue with updating BehaviorSubject not being reflected when called from my service component has been identified

In my HomeComponent, I am currently using *ngIf to switch between 3 components. The focus right now is on the relationship between two of them - the ProductListComponent and the ProductDetailComponent. Inside the ProductListComponent, there is a ProductLis ...

Troubleshooting the issue of Angular 2 error: Cannot access the 'getOptional' property

Currently, I am navigating my way through angular 2 and attempting to define a service named searchservice. I want to inject this service in the bootstap part of my project: import {SearchService} from 'src/service'; Here is the code for the Se ...

Adjusting an item according to a specified pathway

I am currently working on dynamically modifying an object based on a given path, but I am encountering some difficulties in the process. I have managed to create a method that retrieves values at a specified path, and now I need to update values at that pa ...

Can a generic type be utilized to instantiate an object?

In my code, I have a class named Entity as shown below: class Entity { constructor(readonly someValue: string) {} someFunction() {} } Now, I am trying to create a class that will handle these entities and be able to create instances of them. In or ...