搜索敲除数组以查找重复的条目

时间:2019-06-13 02:48:04

标签: javascript arrays knockout.js

我有一个名为self.Employees的KO数组,该数组具有一个显示在屏幕上的用户名列表。用户可以向系统输入新用户,如果名称已经在数组中,我想抛出一个错误。如果文本框为空白,则可以引发错误,但是我似乎无法正确执行搜索。下面是我尝试过的代码。

  var employeeList = [
    new Employee(1, "Jack Johnson"),
    new Employee(2, "Alice Smith"),
    new Employee(3, "Clark Kent"),
    new Employee(4, "Bruce Banner"),
    new Employee(5, "Alan Moore")
  ];

self.Employees = ko.observableArray(employeeList)//要求!

      var match = ko.utils.arrayFirst(self.Employees, function(item)
        {
          return item.employeeName == employee.Name;
        });

    if(match === employee.Name) {
        self.error("Duplicate entry.");
        return;
      }



      // Check if a field is blank before adding to array THIS WORKS
      if(employee.Name == "") {
        self.error("A new employee name is required.");
        return;
      }
      else {
        self.error("");
      }

2 个答案:

答案 0 :(得分:1)

我认为您的代码存在的问题是match设置为员工对象,因此无法像这样进行比较:

// Wrong
if (match === employee.Name) { }

相反,您可以尝试:

// Right
if (match && match.Name === employee.Name) { }

如果您想进行更多的重构,建议将newEmployeeValid作为pureComputed属性来实现。这是一个例子

function Employee(id, name) {
  this.name = ko.observable(name);
  this.id = id;
}

function App(employees) {
 
  this.employeeList = ko.observableArray(employees);
  this.newEmployeeName = ko.observable("");
  
  this.nameValid = ko.pureComputed(
    () => this.newEmployeeName().length > 1
  );
  
  this.nameUnique = ko.pureComputed(
    () => !this.employeeList().some(
            other => other.name() === this.newEmployeeName()
          )
  );
  
  this.error = ko.pureComputed(
    () => {
      if (!this.nameValid()) 
        return `Names should have more than 1 character`;
      if (!this.nameUnique()) 
        return `We already have an employee named ${this.newEmployeeName()}`
        
      return null;
    }
  )
  
  this.employeeValid = ko.pureComputed(
    () => !!this.error()
  );
  
  this.addEmployee = () => {
    this.employeeList.push(
      new Employee(null, this.newEmployeeName())
    )
  }
};

ko.applyBindings(new App([
  new Employee(1, "Jack"),
  new Employee(2, "Alice"),
  new Employee(3, "Clark"),
  new Employee(4, "Bruce"),
  new Employee(5, "Alan")
]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<ul data-bind="foreach: employeeList">
  <li data-bind="text: name"></li>
</ul>

<input data-bind="textInput: newEmployeeName">
<button data-bind="click: addEmployee, enable: employeeValid">Add</button>
<p data-bind="text: error, visible: error" style="color: red"></p>

答案 1 :(得分:0)

您可以尝试使用“某些”功能来检查它是否存在于对象数组中。 可能也更干净。

var name = "check if this name exists"

var itExists = arrayOfObjects.some(employee => employee.name === name);

如果名称作为任何员工姓名位于对象数组内部,这将变为真