基于来自另一个数组的值的打字稿过滤器数组

时间:2019-06-25 12:48:14

标签: arrays typescript array-filter

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

 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

1 个答案:

答案 0 :(得分:0)

这将起作用:

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

您可以看到此功能here

相关问题