微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript浏览类的对象数组以打印每个属性

如何解决JavaScript浏览类的对象数组以打印每个属性

因此,我有一个Worker类,该类扩展了Person类,以便为其提供您在下面看到的所有属性

class Worker extends Person {

    constructor(name,age,address,wage,position) {

        super(name,address);

        this.wage = 0;
        this.position = "";
    }
}

我还有一个EmployeeList类,它基本上是所有Employees的数组:

class EmployeeList {

  //Initialize studentList array
  constructor(empList) {
    this.empList = [];
  }

  //Add studentObject to studentList
  addEmployee(employeeObject) {
    this.empList.push(employeeObject);
  }

  //delete studentObject from studentList
  deleteEmployee(employeeName) {
    let name = this.empList.findindex((employeeName) => {
      return employeeName
    });
    this.empList.splice(name,1);
  }
}

所以我遇到的问题是我能够创建EmployeeList的实例

let myEmployeeList = new EmployeeList();

,并在其中填充员工。但是,我想遍历myEmployeeList中每个Employee的所有属性。我已经尝试过使用Object.keys和Object.Values和Object.entries的混合,但是还没有任何工作。在控制台日志中,我希望输出看起来像这样:

name: George
age: 26
address: 18809 Oakridge Ct.
wage: 20
position: cook
name: Phil
age: 35
address: 4556 Royal Park Ave.
wage: 28
position: chef
name: Lizzy
age: 24
address: 1136 RasBerry Ct.
wage: 22
position: cook

最终,我希望能够按名称或年龄或任何属性进行搜索,所以这就是为什么我试图弄清楚如何遍历所有内容的原因。

我也看到过类似的帖子,但没有发现任何有助于我解决特定问题的帖子。如果已经存在,那么我会为骗子道歉

解决方法

您的帖子中有两件事:

  1. 显示您的Worker

为什么不只将显示方法添加到类WorkerPerson中。并通过迭代遍历并在employeeList中调用其显示方法。

  1. 通过EmployeeList查找属性的值

只需在EmployeeList中添加一个方法来查找您的任何员工属性是否包含您的搜索。像这样的东西:

searchEmployee(search) {
    return empList.filter(employee => {
        return Object.values(employee).includes(search);
    })
}

您将获得一个新列表,其中列出了包含搜索内容的所有员工。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。