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

What is the best way to incorporate an interface in TypeScript that is both callable and has properties?

Given the scenario where an interface is defined as: interface FooWithBar { ():void; bar():void; } I am struggling with writing the implementation. I attempted the following: function foo(){ } foo.bar = function(){ }; This approach did not wo ...

Steps for developing a collaborative module

New to the world of Ionic/Angular development, my project structure looks like this: - src -- /app ---- app.component.ts ---- app.module.ts ---- main.ts ---- ... -- /pages ---- /event-home ------ /event-home.module.ts ------ /event-home.ts event-home.mod ...

Changing the generic type's constraint type in TypeScript to have more flexibility

I have developed a utility type named DataType that takes in a parameter T restricted to the type keyof MyObject. When the key exists in MyObject, DataType will return the property type from MyObject; otherwise, it will simply return T. interface MyObject ...

Tips for retrieving the Solana unix_timestamp on the front-end using JavaScript

Solana Rust smart contracts have access to solana_program::clock::Clock::get()?.unix_timestamp which is seconds from epoch (midnight Jan 1st 1970 GMT) but has a significant drift from any real-world time-zone as a result of Solana's processing delays ...

Assign a value using the select component from Material UI

I just finished creating a dropdown menu const [selectedValue, setSelectedValue] = useState(''); const handleSelectionChange = (e: any) => { //setSelectedValue(e) console.log('value', selectedValue) } .... <Fo ...

The property 'filter' is not recognized on the 'Object' type. An attempt to filter the response was made

Trying to fetch data from a JSON file that matches the player's name in the URL, such as localhost:4200/players/Febiven, should only retrieve information about Febiven. The code is written in Angular 6. The current code snippet is as follows: player ...

What is the best way to initiate a dialog within the handleSubmit function?

In my project, I have a component called SimpleDialog which is defined in the File.tsx file. export default function SimpleDialog() { const handleSubmit = (event: any) => { <SimpleDialog />; } return( <form> <Button type="submit& ...

Running into compilation issues when incorporating ipcRenderer into an Angular 15 and Electron 22 application

I'm facing an issue while trying to utilize ipcRenderer in an Angular service within my Electron project. When attempting to use the standard builder, I encounter the following error message: BREAKING CHANGE: webpack < 5 used to include polyfills f ...

Creating a map in Typescript initialized with a JSON object

In my Typescript class, there is a map that I'm trying to initialize: public map:Map<string,string>; constructor() { let jsonString = { "peureo" : "dsdlsdksd" }; this.map = jsonString; } The issue I'm encounte ...

The promise briefly returns a placeholder object before resolving with the actual response

Currently, I am working on a simple check to determine whether myAnswer contains an answer. The checking functionality is operating smoothly; however, the issue arises in the final function that aims to return the string obtained from myAnswer. Instead of ...

What is the best way to transfer an array of objects between two components in React?

I've exhausted all the solutions found online, but I'm still facing a persistent issue. Despite my efforts, whenever I try to log information in another component, it keeps showing as undefined. (Just to clarify, the data being dealt with is an ...

Using Pydantic to define models with both fixed and additional fields based on a Dict[str, OtherModel], mirroring the TypeScript [key: string] approach

Referencing a similar question, the objective is to construct a TypeScript interface that resembles the following: interface ExpandedModel { fixed: number; [key: string]: OtherModel; } However, it is necessary to validate the OtherModel, so using the ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

Make sure to wait for a Promise to resolve before initiating another Promise within a for loop in Angular

Issue: I am trying to call multiple APIs in sequence within a for loop and need each API call to wait for the previous one to resolve before making the next call. Within my code, I have a for loop that calls a Get API to generate documents on the server s ...

Error message: The function ctorParameters.map is not defined

I am currently experimenting with implementing dragula in my angular2 application. Here is the snippet from my code containing the app.module: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@ang ...

How can TypeScript be used to update the values and text of an HTML element?

Is it possible to update specific attributes of an html element using typescript? Below is the code snippet: HTML:- <a ref="#" id="userProfileName" style="padding-top: 0px; padding-bottom: 0px; padding-right: 10px; padding-left ...

Angular 4 scatter chart with multiple data points using Google charts

I'm currently developing a scatter graph in Angular 4 using ng2-google-charts from https://www.npmjs.com/package/ng2-google-charts It seems like this is essentially a wrapper for Google Chart Service. The graph looks great with a few values, but whe ...

Guide to connecting a table to a detailed view in Angular

I've implemented a table in Angular that fetches data from a web api and displays it. My goal is to link the first column, which contains the (sys_id) ID number, to a detailed view of that specific ID. To achieve this, I know I need to make a GET req ...

Implementing ngClass change on click within an Angular component using Jasmine: A comprehensive guide

It seems like the click event is not triggering and the ngClass is not changing to active on the button I am attempting to click. -- HTML: <div class='btn-group' role='group' aria-label=""> <button type='button&apos ...

Tips for sorting and categorizing information within Angular version 14

When I press "All," I want to see the status of P and step 01, along with its type. Thank you very much. This is in HTML: <mat-form-field appearance="outline"> <mat-select (selectionChange)="onChange($event)"> ...