Jeremy
Jeremy

Reputation: 350

Typescript - Check if an object property already exists

I am currently working on a ToDo App in Angular that adds "Todo's" as objects like so and also checks if the value is empty:

addTodo(newTodoLabel) {
    var newTodo = {
      label: newTodoLabel
    };



    if(newTodo.label == '') {  
      this.errorMessage = "Task description can't be empty";
   } else {

    this.todos.unshift(newTodo);
    this.errorMessage = ''; 
    this.infoMessage = "";
   }
 }

It will be added to this array:

   todos = [
    {
      label: 'Add more task attributes'
    }
  ];

And here is the HTML code as well:

<form #formCtrl="ngForm">

<div class="input-append">
<input class ="inputTask" maxlength="80" placeholder="Please enter a task description" type="text" class="form-control" #newTodo required />

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

Now my question is, how can I also check if the same property already exists in this array? (so that two tasks with the same name can't be added)

Upvotes: 0

Views: 4400

Answers (2)

andrea06590
andrea06590

Reputation: 1299

When you have to check object keys, simply check the object itself, and the object keys you need like :

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

In case you have an array you can check the index too obj[i].label for example. In case you want to check every key at the same time you can look on the obj keys using :

if(obj) {
    Object.keys(obj).map((key) => {
      if(obj[key]) { console.log("your object key exists") }
    })
}

Upvotes: 1

Hassan Imam
Hassan Imam

Reputation: 22534

Before adding a new todo, you can check if it already exists using array#some. If it exists, display error message, otherwise add it.

addTodo(newTodoLabel) {
  var newTodo = {
    label: newTodoLabel
  };

  if(newTodo.label == '') {  
    this.errorMessage = "Task description can't be empty";
 } else {
  //Check for duplicate todos
  var isSame = this.todos.some(function(o){
    return o.label.toLowerCase() === newTodoLabel.toLowerCase();
  });

  if(isSame) {
    this.errorMessage = 'Already conatins the same todo'
  } else {
     this.todos.unshift(newTodo);
     this.errorMessage = ''; 
     this.infoMessage = "";
  }
 }
}

Upvotes: 1

Related Questions