如何比较两个对象数组中的值

时间:2019-07-18 11:00:35

标签: javascript

我有两个对象数组

  arrNew =  [ { RecordId: '181049', DateCreated: 1563447093133 },
              { RecordId: '187020', DateCreated: 1563447093134 } ]

   arrNew2 = [ { RecordId: '181049', DateCreated: 1563447093134 },
               { RecordId: '187020', DateCreated: 1563447093134 },
               { RecordId: '187021', DateCreated: 1563447093134 } ]

我需要做的是从第一个数组中获取RecordID,从第二个数组中获取RecordId,如果RecordId在两个数组之间匹配则什么也不做,但是我有一条新记录返回true。

for (let index = 0; index < newArr.length; index++) {
    const element = newArr[index];

    for (let index = 0; index < newArr2.length; index++) {
      const element2 = newArr2[index];
      if(element.RecordId == element2.RecordId){
        console.log('true', '1')
      }else{
        console.log('false', '2')
      }
    }
 }

输出

true 1
false 2
false 2
true 1

不是很好

如何纠正?

3 个答案:

答案 0 :(得分:1)

您的代码对不同的循环使用相同的index变量。但是到目前为止,您的幼稚实现看起来还不错。只需使用另一个变量index2进行嵌套循环即可快速解决该问题:

  newArr =  [ { RecordId: '181049', DateCreated: 1563447093133 },
              { RecordId: '187020', DateCreated: 1563447093134 } ]

   newArr2 = [ { RecordId: '181049', DateCreated: 1563447093134 },
               { RecordId: '187020', DateCreated: 1563447093134 } ]

for (let index = 0; index < newArr.length; index++) {
    const element = newArr[index];

    for (let index2 = 0; index2 < newArr2.length; index2++) {
      const element2 = newArr2[index2];
      if(element.RecordId == element2.RecordId){
        console.log('true', '1')
      }else{
        console.log('false', '2')
      }
    }
 }

答案 1 :(得分:1)

您可以取Set的已知RecordId并通过检查集合来过滤数组。

过滤的结果已准备好进行进一步处理。

优点是只有两个循环,一个循环用于生成集合,另一个循环用于获取未知元素,而不是一遍又一遍地迭代一个数组以获取匹配项。

var array1 = [{ RecordId: '181049', DateCreated: 1563447093133 }, { RecordId: '187020', DateCreated: 1563447093134 }],
    array2 = [{ RecordId: '181049', DateCreated: 1563447093134 }, { RecordId: '187020', DateCreated: 1563447093134 }, { RecordId: '187021', DateCreated: 1563447093134 }],
    known = new Set(array1.map(({ RecordId }) => RecordId)),
    unknown = array2.filter(({ RecordId }) => !known.has(RecordId));

console.log(unknown);

答案 2 :(得分:1)

让我们假设您的数组不相等(因为您没有说它们总是相等的),所以我们可以使用较短数组的长度(如果B仅具有3,则尝试将a [3]与b [3]进行比较)其中的对象会出现错误)。

var max = 0; //so we now the max index we can go to

if(arrNew.length > arrNew2.length){
  max = arrNew2.length;
}else{
  max = arrNew.length;
}

for(var i=0;i<max;i++){
  if(arrNew[i].RecordId == arrNew2[i].RecordId)
  {
    console.log(true);
  }else{
    console.log(false);
  }
}