【问题标题】:Search Knockout Array for Duplicate Entries在敲除数组中搜索重复条目
【发布时间】:2019-10-27 14:08:36
【问题描述】:

我有一个名为 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("");
      }

【问题讨论】:

    标签: javascript arrays knockout.js


    【解决方案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>

    【讨论】:

      【解决方案2】:

      您可以尝试“some”函数来检查它是否存在于对象数组中。 它也可能更干净。

      var name = "check if this name exists"
      
      var itExists = arrayOfObjects.some(employee => employee.name === name);
      
      

      如果 name 在对象数组中作为任何员工的姓名,这将成为 true

      【讨论】:

      • 我似乎还有一些挑战。也许我做错了什么。我将使用关于 KO 数组的其他信息更新我的代码
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多