[英]How to compare values in two array of objects
我有兩個對象數組
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
這不是不好
怎么糾正呢?
您的代碼對不同的循環使用相同的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') } } }
您可以使用一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);
假設您的數組不相等(因為您沒有說它們總是相等的),所以我們可以使用較短數組的長度(如果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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.