Guide on creating a condition that displays an alert message if it exists, otherwise, it should be

I am looking to insert data into an array list based on the product id. If the product id already exists in the array list, I need to display an alert message; otherwise, I want to add it to the list. Please provide me with the necessary conditions for this.

public stockDataSource: Array<any> = [];

const stockData: StockTrackingItem = {
    StockTrackingItemId: 0,
    StockTrackingId: 0,
    Sno: this.Sno,
    ProductId: stock.productId,
    SKU: stock.sku,
    SKUId: stock.skuId
};

if (this.stockDataSource.length === 0) {
    this.stockDataSource.push(stockData);
} else {
    for (let index = 0; index < this.stockDataSource.length; index++) {
        if (this.stockDataSource[index].ProductId === stockData.ProductId) {
           this.alertService.warnAlert("Product already exists");
            break;
        }
    }
    this.stockDataSource.push(stockData);
}

Answer №1

Here is one approach to achieve this task. Have you considered whether it's necessary to trigger an alert for each item in the array? It might be more efficient to gather existing ids in an array and then display them all at once. Ultimately, this decision depends on the overall design of your application.

this.stockDataSource.forEach(data => {
    if(data.ProductId) {
        alert("This id exists");
    } else {
        this.array.push(data);
    }
}

Answer №2

Utilizing a filter to determine if the existing stockDataSource list contains the productId is a recommended approach for validation. It is anticipated that both the stockDataSource and stockData will possess dynamic values.

    public stockDataSource: Array<any> = []; // The content of this array is subject to change

    const stockData: StockTrackingItem = {   // The content of this object is dynamic
                            StockTrackingItemId: 0,
                            StockTrackingId: 0,
                            Sno: this.Sno,
                            ProductId: stock.productId,
                            SKU: stock.sku,
                            SKUId: stock.skuId
                        };
const ArrayListToBeAdded = [{...stockData},{...stockData}] // An array containing copies of stockData items of type StockTrackingItem to be inserted  // Modify this according to your data insertion requirement
ArrayListToBeAdded.forEach(data=>decidingFn(data));

    //The code below pertains to filtering and verifying the matching product ids in stockDataSource list


        decidingFn(stockData:StockTrackingItem){
        const productMatchList=stockDataSource.filter(stock=>stock.ProductId==stockData.ProductId);

                    if(productMatchList.length===0){
                    this.stockDataSource.push(stockData);
                    }else{
                    this.alertService.warnAlert("Product already exists");
                    }
        }

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

The Angular service retrieves only the default values

I'm currently following an Angular tutorial and encountering some issues. Problem #1: The problem arises when using two services, recipe.service.ts (handles local data manipulation) and data-storage.service.ts (stores data in Firebase). When the getR ...

Obtaining the status code from an HTTP request in Angular 2

I'm struggling to successfully make an HTTP request and either return the response object or a boolean value. I am having trouble handling errors as my `handleError` function is not functioning properly. This is what my code currently looks like: Th ...

When using nodejs with sqlite3, the first callback parameter returns the class instance. How can this be resolved in order to prevent any issues?

Exploring a TypeScript class: class Log { public id: number; public text: string; construct(text: string){ this.text = text; } save(){ db.run( `insert into logs(text) values (?) `, this.text, ...

Postgres Array intersection: finding elements common to two arrays

I'm currently developing a search function based on tags, within a table structure like this CREATE TABLE permission ( id serial primary key, tags varchar(255)[], ); After adding a row with the tags "artist" and "default," I aim ...

What is the correct syntax for declaring a variable within a switch statement in TypeScript?

How can I properly use a switch statement in TypeScript to assign a new variable a value? For example: let name: string switch(index) { case 0: name = "cat" case 1: name = "dog" .... } I keep getting the err ...

What is the best way to combine async/await with a custom Promise class implementation?

I've created a unique Promise class. How can I incorporate it with async/await? type Resolve<T> = (x: T | PromiseLike<T>) => void type Reject = (reason?: any) => void class CustomizedPromise<T> extends Promise<T> { ...

How to perfectly align a button at the center and position it in the forefront?

I'm attempting to place a button in front of my video and center it on the video. I've tried using position-relative to bring it in front and flex to center it vertically and horizontally, but it's not working as expected. The z-index is cor ...

The error message "No provider found for MatSidenavContainer within mat-sidenav-content" is being

app.component.html <mat-side-nav-container> <mat-sidenav #sidenav> <mat-nav-list> <a mat-list-item [routerLink]="'/accounts'"> Accounts </a> <a mat-list-item [routerLink]="&ap ...

The height of the Bootstrap column does not extend to its full potential

Having an issue: https://i.sstatic.net/L45Ii.png In the image, you can see that the column is not taking up the full height. The left side shows what I currently have, and the right side shows what I want to achieve. Here's the source code that corr ...

Using HttpClient to make a POST request to a json file on a local server

I have a `data.json` file located in the assets folder of my Angular application. The file path is as follows: MyApp => src => assets => data.json I am trying to make a `POST` request to this file using HttpClient in a component within the app ...

Typescript: searching for a specific type within an array of objects

The title may be a bit unclear, but I'm struggling to find a better way to explain it. I have a predefined set of classes from a third-party library that I cannot modify. The specific content of these classes is not relevant, as it's just for i ...

What is the best way to access a variable from script A within script B using TypeScript?

I am looking to extract a variable from another script in order to generate the subsequent section of the page based on this data. Below is the code snippet that retrieves data from an API: import Axios from "axios"; import React from "reac ...

Dividing an array into categories with typescript/javascript

Here is the initial structure I have: products = [ { 'id': 1 'name: 'test' }, { 'id': 2 'name: 'test' }, { 'id' ...

Getting the auto-incremented field value of the current record after insertion in Angular2+ ASP.net can be achieved by utilizing

Currently facing an issue where I need to retrieve the auto-incremented field value of the last inserted row without passing it during insertion, as it is generated automatically. In order to achieve this, I first add data to the table and then call a meth ...

How do I insert a new column into the result set of a query in Prisma?

Imagine a scenario where there are two tables: User, which has fields for name and Id, and Post, which has fields for name and content. These tables are connected through a many-to-many relationship (meaning one post can have multiple users/authors and eac ...

Having difficulty retrieving the value of the final <th> element within a table or list

I am encountering an issue where I cannot retrieve the value of the last item and update the next item accordingly. I have attempted using :last-child, but it does not provide the desired values. if ($("tbody").children().length == 0) { var ...

I am encountering a TypeScript error when using the createRef() method in React JS

Encountering some TypeScript warnings with the following dependencies: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8df9f4fde8feeeffe4fdf9cdbea3b8a3bf">[email protected]</a>, <a href="/cdn-cgi/l/email-protect ...

What could be the reason for Angular Router to receive query parameters twice?

I have an application that consists of two pages with lists. On Page A, clicking on an item will display the corresponding detail page. The detail page contains a list of sub-items, and clicking on any sub-item navigates to Page B with the sub-item's ...

NodeJS Express throwing error as HTML on Angular frontend

I am currently facing an issue with my nodejs server that uses the next() function to catch errors. The problem is that the thrown error is being returned to the frontend in HTML format instead of JSON. I need help in changing it to JSON. Here is a snippe ...

What is the best way to adjust the bootstrap column size using variables and decide when to insert a new row dynamically?

I am struggling to dynamically change the number of columns in a row based on the already sorted array. I want the layout to look like the example at the bottom, with Comedies spanning two rows, Action spanning three, and Horror only one row. However, I ca ...