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

Incorporating the Revolution Slider jQuery plugin within a Vue.js environment

Currently, my goal is to transform an html project into a vue application. The initial project utilizes a jquery plugin for Revolution slider by including them through script tags in the body of the html file and then initializing them: <script type= ...

What is the reason behind a TypeScript compiler error being triggered by an 'if-else' statement, while a ternary operator construct that appears identical does not raise any errors?

My function is designed to either return a value of IDBValidKey or something that has been converted to IDBValidKey. When I use the ternary operator to write the function, it works fine. However, if I try to write it as an if-else statement, it causes a co ...

Implementing Java script for onkeypress event in a search bar that does not require a button

Currently utilizing this javascript to trigger an event on key press: function myFunction() { if (window.event || window.event.keyCode == 13) { changeSource(); } } function changeSource(){ document.getElementById("frame1").src="Log-In. ...

Exploring AngularJS: Effortlessly Retrieving Object Values

HTML: <div ng-app = "" ng-controller = "personController"> <p>Persoon: <select ng-model="persoon"> <option ng-repeat="person in persons">{{person.FirstName}} {{person.FamilyName}}</option> & ...

Tips for sending props to Material UI components

Hey there! I'm currently working on a progressbar component that utilizes animations to animate the progress. I've styled the component using Material UI classes and integrated it into another component where I pass props to customize the progres ...

Tips on sending references from child to parent components in ReactJS

Upon rendering my child component, I aim to focus on the input box right away. To achieve this, I am attempting to pass the ref of the input box up to its parent component, which contains a modal. My goal is to focus on the input field upon entering the mo ...

What are the methods for showcasing data within a string?

I'm struggling to figure out how to display the column names from a JSON file. Currently, all the column names are being displayed in one column, and empty fields are showing up for some reason. How can I format it so that the column names are listed ...

Error encountered during Ionic iOS build caused by google-plus plugin

Seeking solution for the error below, unsure where to begin. While attempting to compile my Ionic project for iOS, encountering the following issue: $ ionic cordova build ios .... /Plugins/cordova-plugin-googleplus/GooglePlus.h:2:9: fatal error: 'Goog ...

Assigning value to a member variable in a TypeScript Angular class

Currently, I am in the process of learning Angular. To enhance my skills, I am developing a simple web application using Angular and Spring Boot. One challenge I encountered is assigning a variable to the member variable of a Class. import { Injectable } f ...

Utilizing unique layouts for specific views in sails.js and angular.js

I am currently working on a Sails.js + Angular.js project with a single layout. However, I have come across different HTML files that have a completely different layout compared to the one I am using. The layout file I am currently using is the default la ...

Distributing JWT to the recipient using Express

Allow me to provide you with an overview of my application, which is quite straightforward. The main concept revolves around a user inputting their accountname and password into an html form on the /Login page like so: <form action="/Login" m ...

Utilizing the power of Ajax for enhancing table sorting and filtering functionality

Having an issue using JQuery tablesorter to paginate a table with rows fetched from the database. //list players by points (default listing) $result=mysql_query("select * from players order by pts_total") or die(mysql_error()); echo "<table id='li ...

Recalling the layout following the user's computer restart

I am creating a simple online editing tool (similar to Microsoft Outline) for coursework and I would like the outline details to be saved even if the user restarts the system. How can I achieve this? <html> <head> <title>Editor</ ...

I need to know how to create a patch request in Vue.js and simultaneously modify the marks input for specific individuals by using v-model

Hello there, I am currently developing a student assessment input form using vuejs, express, and mongoDB. The backend API is complete and functioning properly when tested with postman. Here is the code: // UPDATE MARKS router.patch('/:studentId' ...

I'm unable to modify the text within my child component - what's the reason behind this limitation?

I created a Single File Component to display something, here is the code <template> <el-link type="primary" @click="test()" >{{this.contentShow}}</el-link> </template> <script lang="ts"> imp ...

What is the best method to add data to a child array located within a nested array?

Struggling to create an array that will display data in the following format: Healthcare -- Insights driven by data for improved healthcare -- Urban Analytics Transport -- Urban Analytics Cities -- Urban Analytics I have attempted ...

Exploring the synergies between Angular Dragula and utilizing the $index property

Currently, I have implemented an ng-repeat of rows that can be rearranged using Angular Dragula. Despite successful drag-and-drop functionality, the $index in ng-repeat remains constant for each item even after reordering. The screenshot below depicts the ...

Modifying the selected color of DropDownMenu List items

Hey there! I'm currently trying to modify the color of a material-ui element that is selected, but I'm having trouble finding any resources on how to accomplish this. My goal is to switch this pinkish shade to a more soothing blue hue. Update: I ...

What is the process of uploading a file from a Vue.js app to the local public disk in Laravel?

Hello there, I am looking to upload a file from a Vue.js app to the local public directory of Laravel and only store the unique name in MySQL upon form submission. However, I am unsure how to achieve this using JavaScript. // Template Tag <input type= ...

Setting the base URL in Next.js according to an environment variable: a step-by-step guide

I currently have a Strapi backend and Next.js frontend application deployed on DigitalOcean. Within DigitalOcean, I have configured an environment variable for the frontend: API_URL = ${APP_URL}/api To generate the base URL, I retrieve this variable using ...