【问题标题】:Typescript filter array based on value from another array基于来自另一个数组的值的打字稿过滤器数组
【发布时间】:2022-05-01 04:48:06
【问题描述】:

这个问题已经被问过很多次了,但我无法解决。
我有两个数组,第一个是:

 first= [
      {
        id:1, descrizione: "Oggetto 1", 
        codiceAzienda: "Codice 1",
        dataInserimento:"01-01-2019",
        dataAggiornamento: "01-01-2019"
      },
      {
        id:2, descrizione: "Oggetto 2", 
        codiceAzienda: "Codice 2",
        dataInserimento:"01-01-2019",
        dataAggiornamento: "01-01-2019"
      },
      {
        id:3, descrizione: "Oggetto 3", 
        codiceAzienda: "Codice 3",
        dataInserimento:"01-01-2019",
        dataAggiornamento: "01-01-2019"
      },
      {
        id:4, descrizione: "Oggetto 4", 
        codiceAzienda: "Codice 4",
        dataInserimento:"01-01-2019",
        dataAggiornamento: "01-01-2019"
      },
      {
        id:5, descrizione: "Oggetto 5", 
        codiceAzienda: "Codice 5",
        dataInserimento:"01-01-2019",
        dataAggiornamento: "01-01-2019"
      }
    ]

第二个是这样的:

second = [
          {
            id:1, descrizione: "Oggetto 1"
          },
          {
            id:3, descrizione: "Oggetto 3"
          }
        ]

我想要实现的是拥有一个数组,其中只有第一个对象的 id 等于第二个对象之一。所以结果是:

final= [
          {
            id:1, descrizione: "Oggetto 1", 
            codiceAzienda: "Codice 1",
            dataInserimento:"01-01-2019",
            dataAggiornamento: "01-01-2019"
          },
          {
            id:3, descrizione: "Oggetto 3", 
            codiceAzienda: "Codice 3",
            dataInserimento:"01-01-2019",
            dataAggiornamento: "01-01-2019"
          }
        ]

我试过这样做:

final= first.filter(ogg => second.map(y => y.id).includes(ogg.id));

但结果我拥有第一个数组的所有对象。我也试过array.some():

final= first.filter(ogg => second.some(id => ogg.id == id));

在这种情况下,最终的数组是空的。
Example of the second case

【问题讨论】:

  • 这似乎不是打字稿问题,因为有任何类型的参考,是一个简单的 JS 问题

标签: javascript arrays array-filter


【解决方案1】:

这将起作用:

const final = first.filter(x => second.find(y => y.id === x.id))

你可以看到这个工作here

【讨论】:

  • 嗨,它不起作用...它不过滤对象,最终数组包含第一个中的所有对象
  • @Dseaster 查看示例中的控制台选项卡。这就是您在问题中要求的结果。
  • 是的,我看到了,但是如果我把它写在我的代码中,它就不起作用,我不明白为什么
  • 我认为这个答案是正确的,因为它有效,即使我发现我的问题是别的问题,所以我的解决方案也是正确的。但是不承认你的努力/时间是不公平的,所以非常感谢你。
猜你喜欢
  • 2022-01-22
  • 2018-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
相关资源
最近更新 更多