簡體   English   中英

打字稿-檢查對象屬性是否已經存在

[英]Typescript - Check if an object property already exists

我目前正在Angular上的ToDo應用程序上工作,該應用程序將“ Todo's”添加為此類對象,並且還檢查該值是否為空:

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 = "";
   }
 }

它將添加到此數組:

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

這也是HTML代碼:

<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>

現在我的問題是,我如何還可以檢查此數組中是否已存在相同的屬性? (因此無法添加兩個具有相同名稱的任務)

在添加新的待辦事項之前,您可以使用array#some檢查它是否已經存在。 如果存在,則顯示錯誤消息,否則添加它。

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 = "";
  }
 }
}

當您必須檢查對象鍵時,只需檢查對象本身以及所需的對象鍵即可:

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

如果您有數組,也可以檢查索引,例如obj [i] .label。 如果您想同時檢查每個鍵,可以使用以下命令查看obj鍵:

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

您的問題不是特定於Angular,而是與JavaScript數組的查詢有關。 以下帖子已經回答了這個問題

如何確定Javascript數組是否包含屬性等於給定值的對象?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM