Working with Angular to add various items to an array based on multiple conditions

Currently, I am a beginner in TypeScript and currently involved in an Angular project.

As part of my work, I need to make an API call and perform various operations on the received data:

public data_Config: IConfig[] = [];

this.getService.Data(input).subscribe(
    data => {
        this.data_Config = data;
        this.data_Config.forEach(itm => { 
            if(itm.aFl == 'Y'){
                itm.Levels.push('A')
            }
            if(itm.bFl == 'Y'){
                itm.Levels.push('B')
            }
            if(itm.cFl == 'Y'){
                itm.Levels.push('C')
            }
        });
        this.dataSource_prgmConfiguration = new MatTableDataSource(this.data_prgmConfiguration);
        this.dataSource_prgmConfiguration.paginator = this.paginatorPrgmConfiguration;
        this.dataSource_prgmConfiguration.sort = this.sortPrgmConfiguration;
});

IConfig represents a type with numerous properties including 10-12 flag properties such as aFl, bFl, and cFl. My current implementation involves checking each flag property individually using if conditions. However, given the high number of flags, I am exploring better alternatives. Is there a more efficient way to handle this scenario?

Integration of IConfig

export interface IConfig {
    TypeNm: string;
    aFl: string;
    bFl: string;
    cFl: string;
    dFl: string;
    eFl: string;
    fFl: string;
    gFl: string;
    hFl: string;
    PlaceHolder: string;
    Association: string;
    ActiveFl: string;
    Actions: string;
    AssociatedProgramsStr?: string;
    Levels?: string[];
}

Answer №1

Here's a way to achieve the desired outcome:

Object.keys(this.dataConfig).filter(key => key.indexOf('Fl') != -1).forEach(flag => {
    if(this.dataConfig[flag] == 'Y')
        itm.Levels.push(this.dataConfig[glag].charAt(0).toUpperCase());
}

This code snippet assumes that all your flags are labeled with the same format of xFl where x represents a letter, and the flag pertains to the uppercase version of that specific letter which should be added to the Levels array. Simply put, you extract the keys corresponding to flags from your object, iterate over them, and verify the condition mentioned above.

Answer №2

There are various approaches to consider depending on the specific requirements,

If we assume that the IConfig interface only consists of boolean properties like aF1, bF1, cF1 ..., then a possible solution could look like this:

Option : 1

this.data_Config.forEach(item => { 

    Object.keys(item).forEach(key=>{
        if(item[key] === 'Y'){
            item.Levels.push('whatever'); // The exact representation of 'A','B' is unclear
        }
    })
    
});

Option: 2

In case the IConfig interface contains other non-boolean properties such as height, width, you can follow this approach:

const boolProperties = ['aF1', 'bF1', 'cF1']; // define boolean properties in an array

this.data_Config.forEach(item => { 

        Object.keys(item).forEach(key => {
            if(boolProperties.includes(key) && item[key] === 'Y'){
                item.Levels.push('whatever'); // The true meaning of 'A','B' is not specified
            }
        })
        
});

Answer №3

If you're working with TypeScript, you have the ability to define an ENUM in the following manner.

enum myEnum {
  val1 = 'Value1',
  val2 = 'Value2'
}

You can then iterate through a set of data and extract the values that match your criteria.

let matchingValues: any[] = [];
myData.forEach(item => {
 if (item === 'Y'){
    matchingValues.push(myEnum[item]); 
 }
});

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

How to trigger a file download instead of opening it in a new tab when clicking on a txt or png file in AngularJS

After retrieving my file URL from the backend API, I am trying to enable downloading when the user clicks a button. Currently, the download function works smoothly for Excel files (`.xlsx`), but for text (`.txt`) files or images (`.jpeg`, `.png`), it only ...

What could be causing a compile error in my React and TypeScript application?

I recently downloaded an app (which works in the sandbox) from this link: https://codesandbox.io/s/wbkd-react-flow-forked-78hxw4 However, when I try to run it locally using: npm install followed by: npm start I encounter the following error message: T ...

Guide to displaying the value of a field in an object upon clicking the inline edit button using TypeScript

Is it possible to console log a specific attribute of an object when clicking on the edit button using the code below? Please provide guidance on how to utilize the index to access the value of "name". Refer to the last line in the code with the comment. ...

How to Create Smooth Transitions for Text Arrays using jQuery's Fade In and Fade Out Features

I need to loop through an array of text and apply jQuery's fadeIn and fadeOut functions to each element. var greetings = ["hi, I'm", "bonjour, je m'appelle", "hallo, ich heiße"] The HTML structure I want is as follows: <h2><span ...

Angular is not programmed to automatically reflect updates made to my string array

let signalRServerEndPoint = 'https://localhost:44338'; this.connection = $.hubConnection(signalRServerEndPoint); this.proxy = this.connection.createHubProxy('MessagesHub'); this.proxy.on("ReceiveMessage", (message) => { ...

Creating an HTML element within a three.js globe

I have a globe created using three.js Reference: I am trying to display an HTML div at a specific latitude/longitude on the globe. Can someone guide me on how to position the div at a particular lat/long? What I've attempted: I'm currently stu ...

Exploring the differences in performance between React hooks and React classes

Currently, I am delving into understanding React hooks and could use some assistance with comprehending whether every time a React function renders, the hook state resets. Below is a brief example related to fixing a header on scroll: class Header extends ...

React Leaflet causing a frequent map refresh due to context value updates

When I use map.on('moveend') to update the list of markers displayed in another component, I encounter a refreshing issue. The context in my project contains two arrays - one filtered array and one array with the markers. When I try to update the ...

Should Redux Reducer deep compare values or should it be done in the Component's ShouldComponentUpdate function?

Within my React Redux application, I have implemented a setInterval() function that continuously calls an action creator this.props.getLatestNews(), which in turn queries a REST API endpoint. Upon receiving the API response (an array of objects), the actio ...

Best resolutions and formats for Nativescript-Vue application icons

I'm a newbie when it comes to Nativescript, and I'm looking to change the icon for my app. After doing some research, I found this command: tns resources generate splashes <path to image> [--background <color>] This command seems li ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

Discovering uncategorized elements using javascript

Let's say I have a piece of HTML with some content that is not wrapped in any tags, like this: <html> <body> <p>text in a tag</p> other text outside any tag </body> </html> Is there a way to access the untagged el ...

Is it necessary to delay until the entire page finishes loading in Selenium 3?

public boolean CheckPageLoadStatus(){ final ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() { public Boolean apply(final WebDriver driver) { return ((JavascriptExecutor) driver).executeScr ...

The error occurs when Facebook and Twitter iframes are attempting to access and set 'document.domain'

When attempting to add Tweet and Facebook Like buttons to the project I'm working on, everything appears to be functioning properly. However, upon clicking the buttons, a JavaScript error occurs: Unsafe JavaScript attempt to access frame with URL htt ...

Issue with pushing inner list<object> in Knockout version 3.2.0

Currently, I am working with knockout.js on an ASP application. The issue I am facing involves a list of objects returned by the controller action to the view, where the objects in the list point to another list of objects. My struggle lies in adding new o ...

What is causing the 'Invalid Hook Call' error to appear in React?

I have recently started learning React and I am currently working on converting a functional component into a class component. However, I encountered an error message that says: Error: Invalid hook call. Hooks can only be called inside of the body of a fu ...

Unable to retrieve data from database using Angular 4

I am currently working with Angular 4 and using a MySQL database. This is my service: service.ts getData(){ return this.http.get('http://example/users.php').map(res=>{ return res.json(); }).catch(err=>{ return err.jso ...

Can Vuejs delay the calculation of a computed property until the component is "ready"?

Within my Vue.js application, I have a `computed` property that relies on a value fetched from an AJAX call. I am looking for a way to delay the calculation of this `computed` property until after the `ready` method has completed. While everything is fun ...

Leverage the power of forkJoin alongside activatedRoute

One of the observables I'm working with is the following: formData$ = forkJoin([ this.httpService.getProgramsLevelsList(), this.httpService.getProgramsTypesList(), this.httpService.getQuestionnaireReasonsList() ]).pipe( tap((res: any) => ...

Concealing a Div element without the use of Jquery or JavaScript

I have an Upper and Lower div in my HTML code. I am trying to display the Lower div only if the Upper div is present, otherwise hide it. Is there a way to achieve this using CSS without using Jquery or Javascript? Note: No modifications should be made t ...