简体   繁体   English

两个对象数组的打字稿差异

[英]Typescript difference of two object arrays

I have two object arrays and want to find the items that are missing in the second array but are part of the first array,basically array1-array2.I tried to use filter but I'm unable to get the desired result.Please help.Thanks in advance. 我有两个对象数组,想要找到第二个数组中缺少但属于第一个数组的项,基本上是array1-array2。我尝试使用过滤器,但无法获得所需的结果。请帮助。提前致谢。

Here is the code: 这是代码:

 testData=[
       {id: 0, name: "policy001"},
       {id: 2, name: "policy002"}];
       sourceData= [
          {id: 0, name: "policy001"},
          {id: 2, name: "policy002"},
          {id: 3, name: "policy003"},
          {id: 4, name: "policy004"},
          {id: 5, name: "policy005"}, 
      ];

      let missing = sourceData.filter(item =>  testData.indexOf(item) < 0);
      console.log("Miss")
      console.log(missing )//Returns the sourceData instead of diff.

The reason your code did not work is that object inside array are "addresses" to the objects. 您的代码不起作用的原因是数组内的对象是对象的“地址”。 So of course the indexOf did not work 所以当然indexOf不起作用

try below: 请尝试以下方法:

let missing = sourceData.filter(a => !testData.find(b => a.id === b.id));

Try findIndex() : 尝试findIndex()

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. findIndex()方法返回满足提供的测试功能的数组中第一个元素的索引。 Otherwise, it returns -1, indicating that no element passed the test. 否则,它返回-1,表示没有元素通过测试。

 testData = [{ id: 0, name: "policy001" }, { id: 2, name: "policy002" } ]; sourceData = [{ id: 0, name: "policy001" }, { id: 2, name: "policy002" }, { id: 3, name: "policy003" }, { id: 4, name: "policy004" }, { id: 5, name: "policy005" }, ]; console.log(sourceData.filter(item => testData.findIndex(x => x.id == item.id) < 0)) 

You're getting this undesired behavior because what you're doing in your filter is comparing the items' references rather than their values. 之所以出现这种不良行为,是因为您在过滤器中所做的是比较项目的引用而不是它们的值。 if you want to compare that those objects are actually identical in values (because they have different references), you need to do the following: 如果要比较那些对象的值实际上是相同的(因为它们具有不同的引用),则需要执行以下操作:

let missing = sourceData.filter(sourceItem => 
  testData.every(testItem =>
    testItem.id !== sourceItem.id && testItem.name !== sourceItem.name
  )
)

this means - filter out those element of sourceData, for which none of the elements in testData has the same id or name. 这意味着-过滤出sourceData的那些元素,其testData中的所有元素都没有相同的ID或名称。 They are "missing". 他们“失踪”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM