Typescript - 检查对象属性是否已存在

时间:2018-01-26 12:31:22

标签: angular typescript

我目前正在开发Angular的ToDo应用程序,它添加了" Todo"像这样的对象,并检查值是否为空:

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>

  

现在我的问题是,如何检查此数组中是否已存在相同的属性? (这样就不能添加两个同名的任务)

3 个答案:

答案 0 :(得分:1)

在添加新待办事项之前,您可以使用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 = "";
  }
 }
}

答案 1 :(得分:1)

当你必须检查对象键时,只需检查对象本身,以及你需要的对象键:

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") }
    })
}

答案 2 :(得分:0)

您的问题不是Angular特定的,而是与查询JavaScript数组有关。这个问题已在以下文章中得到解答

How to determine if Javascript array contains an object with an attribute that equals a given value?