Typescript - Verifying the existence of an object property

I am currently developing a task management application in Angular where tasks are added as objects and checked for empty values using the following code:

addTodo(newTaskLabel) {
    var newTask = {
      label: newTaskLabel
    };



    if(newTask.label == '') {  
      this.errorMessage = "Task description cannot be blank";
   } else {

    this.tasks.unshift(newTask);
    this.errorMessage = ''; 
    this.infoMessage = "";
   }
 }

The tasks are stored in this array:

   tasks = [
    {
      label: 'Add more details to tasks'
    }
  ];

Below is the accompanying HTML code:

<form #formCtrl="ngForm">

<div class="input-append">
<input class ="inputTask" maxlength="80" placeholder="Enter task description" type="text" class="form-control" #newTask required />

<button class="buttonTask" (click)="addTodo(newTask.value); newTask.value=''" type="button" class="btn btn-primary form-control" >Add Task</button>

My query now is, how can I implement a check to ensure that duplicate tasks with the same name are not added to the array?

Answer №1

Prior to adding a new task item, you have the option to verify its existence by utilizing array#some. Should it already be present, an error message will be displayed; otherwise, the task will be added.

addTask(newTaskLabel) {
  var newTask = {
    label: newTaskLabel
  };

  if(newTask.label == '') { 
    this.errorMessage = "Description of task cannot be left empty";
 } else {
  //Check for duplicate tasks
  var isDuplicate = this.tasks.some(function(item){
    return item.label.toLowerCase() === newTaskLabel.toLowerCase();
  });

  if(isDuplicate) {
    this.errorMessage = 'A similar task already exists'
  } else {
     this.tasks.unshift(newTask);
     this.errorMessage = ''; 
     this.infoMessage = "";
  }
 }
}

Answer №2

To effectively verify object keys, one should examine the object itself along with the specific keys required. For instance:

if (obj && obj.label && obj.label !== '') { myFunction() {} }

If dealing with an array, you can also confirm the index like obj[i].label. For checking all keys simultaneously, refer to the object keys using:

if(obj) {
    Object.keys(obj).map((key) => {
      if(obj[key]) { console.log("your object key 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 TN-Models-FP error message states that it is not allowed to use the `create` model without an associated `entity` model

Utilizing the TN-models-fp library to construct a basic api inspired by the provided examples, here is my implementation in api.ts: import { axios } from '../axios-instance' import { createApi } from '@thinknimble/tn-models-fp' import { ...

"Learn the process of uploading, saving, and displaying images using the powerful combination of Mongoose, Express, Angular 4,

For my app, I am utilizing Mongoose, Express, Aurelia, and NodeJS, but I consider myself a beginner in this field. One of the components I'm working on involves implementing CRUD operations that require uploading an image file. Once saved to Mongoose ...

The challenge of determining the best approach for creating local routes and resolving conflicts

The routes in my code are defined as follows @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class CartRoutingModule implements Resolve<ServiceCart> { constructor(private service: CartService) {} re ...

Difficulty Determining Literal Types that Expand a Union of Basic Data Types

Below are the components and function I am working with: interface ILabel<T> { readonly label: string; readonly key: T } interface IProps<T> { readonly labels: Array<ILabel<T>>; readonly defaultValue: T; readonly onChange ...

How do I connect with the global error handling in Vue?

Within my Vue2 application, I am seeking a method to capture global Vue errors and transmit them to a logging or monitoring service such as Sentry. After attempting to overwrite the global error handler of Vue, I noticed that console logs were no longer a ...

Issue encountered with TinyMCE integration in Angular 2

As a newcomer to Angular 2, I recently attempted to integrate the TinyMCE editor into my project. I diligently followed the instructions outlined in this guide to create and implement the TinyMCE component: Despite meticulously following each step, I enc ...

Issues with Angular CLI production build causing JavaScript and CSS links to not function properly

I am currently utilizing the Angular CLI to compile my Angular application into JS and CSS files. The command ng build --environment prod is being used for compilation. Upon examining the index.html file located in the dist directory, I observed that the ...

Discover the power of sharing a service instance in Angular 2 RC5

In the past, I shared a service instance by declaring it as a viewInjectors within my @Component like so: @Component({ selector: 'my-sel', viewInjectors: [SharedService], templateUrl: 'template.html', pipes: [MyPipe] }) ...

Troubleshooting: My Angular 2 Application is Unable to Perform HTTP

I've exhausted all options and I'm still unable to send an http request to my node server on heroku. I can access the route manually, so it's not an issue with the server. Below are snippets of my service and page: **Class is subscription.s ...

Error encountered while parsing JSON data due to data type inconsistency

I am currently working on converting JSON data called JsonData that includes time-series of parameters: [ [ timestamp1, [ [paramset1, ...], [paramset2, ...], ...] ], [ timestamp2, [ [paramset1, ...], [paramset2, ...], ...] ], ... ] into a new struc ...

Nrwl NX: Enabling seamless integration of style variables between applications and libraries

Let's cut to the chase: I'm looking to create my library components without specific colors. To achieve this, I style my components like so: h1 { color: $primary; } However, note that the $primary variable is not defined anywhere in the libr ...

Currently in motion post file selection

I am currently facing an issue with a button that triggers a file selector pop-up. Below is the code snippet: <button mat-raised-button (click)="inputFile.click()">Choose a file</button> <input #inputFile type="file" [style.display]="' ...

What is the best way to enforce input requirements in Typescript?

I am currently facing an issue with two required inputs that need to be filled in order to enable the "Add" button functionality. I have considered using *ngIf to control the visibility of the button based on input values, but it seems to not be working. ...

Whenever I attempt to render a component passed as a prop, I encounter error TS2604

I am attempting to pass a component as a prop to another component in order to wrap the content of a material ui modal This is my attempt so far: import React, { Component } from 'react'; import withWidth, { isWidthDown } from '@material-u ...

Swap out the HTML tags for some Angular 6 text!

I have a specific word in my code that I want to change using an HTML tag and apply the style with the themecolor class. <h2 class="mb-30" [innerHTML]="main_title"></h2> Here is a preview of the result: This is some sample text. I need to ...

Updating the DOM with an EventListener in Angular 5 is not functioning properly

Situation : Utilizing an Angular PWA for communication with an iOS native app via WKWebview. Implementing messageHandlers to facilitate data sharing between TypeScript and Swift logic code. Issue : Employing addEventListener to monitor a specific event on ...

The Content Security Policy directive has blocked the font from loading

After successfully creating an Angular project using angular-cli, I attempted to start the project with npm start. However, I encountered an error message indicating that a font was refused to load. Refused to load the font 'data:font/woff;base64,d0 ...

Angular2 fire fails because the namespace 'firebase' does not export the member 'Promise'

I recently set up Angular 2 Fire on my project. "angularfire2": "^5.0.0-rc.0", Now, in my root module (app module), I have the following setup: export const firebaseConfig = { apiKey: "mykey", authDomain: "....", databaseURL: "...", projectId: ...

I'm encountering an error in TestCafe that says "TypeError: Cannot read properties of undefined (reading 'match')". Which specific segment of my code is causing this issue?

retrieveUrlFromEmailData(emailData:any){ const emailContent = emailData.email_text; const urlPattern = /(https?:\/\/[^\n]*)/; const foundUrl = emailContent.match(urlPattern)[0]; return foundUrl } ...

Problem with overlapping numbers in the Vis network

I am currently working on a project using Angular 8 and Visnetwork. Everything is going well, but I am facing an issue with overlapping numbers on lines. Is there a way to adjust the position of the numbers on one line without separating the lines? Can s ...