【问题标题】:angular 8 - Filter an Array of objects by numberangular 8 - 按数字过滤对象数组
【发布时间】:2020-05-13 22:41:45
【问题描述】:

是否可以在 iseidaCcaa.id 等于给定数字的情况下过滤此列表:

var centers = [
  {
    id: 2,
    nombre: "Centro 2",
    iseidaCcaa: {
      id: 1,
    },
  },
  {
    id: 3,
    nombre: "Centro 3",
    iseidaCcaa: {
      id: 1,
    },
  },
  {
    id: 1,
    nombre: "Centro 1",
    iseidaCcaa: {
      id: 2,
    },
  },
];

我尝试了这个解决方案,但它不起作用

 this.centers = this.centers.filter(element => {
    return element.isiedaCcaa.id == 1;
  })

【问题讨论】:

  • 看起来像是一个错字:isiedaCcaa vs iseidaCcaa
  • @Phix。打败我,正在写一个答案。哈哈。肯定是笔误。 @Oussama,不过我想知道您是否希望使用 find() 而不是 filter() 只返回匹配的第一个元素
  • 也应该检查你的打字稿配置。我看到您将问题标记为 typescript,TS 可能肯定发现了那个错字。
  • @iamcastelli,对不起,我想返回所有匹配数字的元素。
  • 哦,那最好使用过滤器。

标签: javascript angular typescript angular8


【解决方案1】:

您在退货时有错字。

应该是return element.iseidaCcaa.id == 1

虽然我会考虑使用 === 如果 id 将是 int

【讨论】:

    【解决方案2】:

    您按类型 iseidaCcaa 而不是 isiedaCcaa 的属性错误

    var centers = [    {
           "id":2,
           "nombre":"Centro 2",
           "iseidaCcaa":{
              "id":1,
           }
    
        },
        {
           "id":3,
       "nombre":"Centro 3",
       "iseidaCcaa":{
         "id":1,
       }
    },
    {
       "id":1,
       "nombre":"Centro 1",
       "iseidaCcaa":{
         "id":2,
       }
    }
    ]
    
     var centers = centers.filter(element => {
        return element.iseidaCcaa.id == 1;
      })
      
      console.log(centers);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      相关资源
      最近更新 更多