【问题标题】:How do I find an Object in an Array? [duplicate]如何在数组中找到对象? [复制]
【发布时间】:2020-11-24 07:29:39
【问题描述】:

使用角度, 我有一个数组

list: Employee[] = [
    {id: 1, name: "conrad", email: "conrad@test.com", password: "123456", department: "Admin"},
    {id: 2, name: "two", email: "2@test.com", password: "123456", department: "Finance"},
    {id: 3, name: "three", email: "3@test.com", password: "123456", department: "Finance"},
    {id: 4, name: "four", email: "4@test.com", password: "123456", department: "Marketing"},
    {id: 5, name: "five", email: "5@test.com", password: "123456", department: "Marketing"},
    {id: 6, name: "six", email: "6@test.com", password: "123456", department: "Marketing"},
    {id: 7, name: "seven", email: "7@test.com", password: "123456", department: "Service"},
    {id: 8, name: "eight", email: "8@test.com", password: "123456", department: "Service"},
    {id: 9, name: "nine", email: "9@test.com", password: "123456", department: "Service"}
  ];

那么我有一个对象

data = {name: "conrad", email: "conrad@test.com", password: "123456", department: "Admin", id: 1}

如何确定列表中是否存在数据 我试过以下给出未定义的答案

signUp(data) {
    console.log(data);
    console.log(this.list.find(l => l === data));
  }

也尝试了一些,包括。

【问题讨论】:

  • 你不能使用===比较对象
  • 使用 loadash _.isEqual(object, other)
  • This 解释了为什么它不起作用,以及如何解决这个问题:

标签: javascript arrays angular object


【解决方案1】:

只需使用Array.prototype.some() 来检查您的列表中是否包含特定员工-Object

list = [
    {id: 1, name: "conrad", email: "conrad@test.com", password: "123456", department: "Admin"},
    {id: 2, name: "two", email: "2@test.com", password: "123456", department: "Finance"},
    {id: 3, name: "three", email: "3@test.com", password: "123456", department: "Finance"},
    {id: 4, name: "four", email: "4@test.com", password: "123456", department: "Marketing"},
    {id: 5, name: "five", email: "5@test.com", password: "123456", department: "Marketing"},
    {id: 6, name: "six", email: "6@test.com", password: "123456", department: "Marketing"},
    {id: 7, name: "seven", email: "7@test.com", password: "123456", department: "Service"},
    {id: 8, name: "eight", email: "8@test.com", password: "123456", department: "Service"},
    {id: 9, name: "nine", email: "9@test.com", password: "123456", department: "Service"}
  ];
  
  function employeeIsInList(employee, list) {
    return list.some((listEmployee) => {
      return employee.id === listEmployee.id;
    });
  }
  
  console.log(
    'employee with id 3 is in the list, therefore result is',
    employeeIsInList({id: 3, name: "three"}, list)
  ); //true
  
  console.log(
    'employee with id 100 is not in the list, therefore result is',
    employeeIsInList({id: 100, name: "woswasi"}, list)
  ); //false

【讨论】:

    猜你喜欢
    • 2019-05-12
    • 2020-02-07
    • 2020-07-09
    • 2022-01-16
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    相关资源
    最近更新 更多