[英]Javascript Compare two arrays with different sizes and return the items that are not in second array
[英]Angular - Compare two arrays with same number of objects but with different values and return the difference from second array
我有 2 個對象數組
arrayOne = [{objectType: 'License', objectId: 333, objectName: 'Test Object 1', dataType: 'String'}
{objectType: 'Owner', objectId: 334, objectName: 'Test Object 2', dataType: 'String'},
{objectType: 'Location', objectId: 335, objectName: 'Test Object 3', dataType: 'String'}]
arrayTwo = [{objectType: 'LICENSE', objectId: 333, objectName: 'Test Object 1', dataType: 'String'}
{objectType: 'OWNER', objectId: 334, objectName: 'Test Object 4', dataType: 'Value List'},
{objectType: 'LOCATION', objectId: 335, objectName: 'Test Object 3', dataType: 'String'}]
正如我們在arrayTwo
中看到的, objectName
和dataType
發生了變化。 任何屬性都可能發生變化,但 arrays 上的對象數量將始終相同。
所以在這里,我需要從arrayTwo
中提取已通過與arrayOne
進行比較而更改的對象,並將其存儲在一個新的數組中,比如resultsArray
?
我檢查了如何獲取 JavaScript 中對象的兩個 arrays 之間的差異中提供的答案,它只討論基於一個屬性而不是任何屬性獲取差異。 請就此提出建議。 謝謝。
編輯:編輯arrayTwo
為objectType
有大寫字母。 我需要忽略大小寫,結果應該不區分大小寫。 謝謝
一種選擇是遍歷第一個數組元素,通過其 id 找到第二個數組的相同元素,然后檢查其任何屬性是否已更改:
arrayOne = [{ objectType: 'License', objectId: 333, objectName: 'Test Object 1', dataType: 'String' }, { objectType: 'Owner', objectId: 334, objectName: 'Test Object 2', dataType: 'String' }, { objectType: 'Location', objectId: 335, objectName: 'Test Object 3', dataType: 'String' } ] arrayTwo = [{ objectType: 'License', objectId: 333, objectName: 'Test Object 1', dataType: 'String' }, { objectType: 'Owner', objectId: 334, objectName: 'Test Object 4', dataType: 'Value List' }, { objectType: 'Location', objectId: 335, objectName: 'Test Object 3', dataType: 'String' } ]; const changedObjects = arrayOne.filter(obj1 => { const obj2 = arrayTwo.find(x => x.objectId === obj1.objectId); return Object.keys(obj1).some(key => String(obj1[key]).toLowerCase().== String(obj2[key]);toLowerCase()); }). console;log(changedObjects);
編輯:上面的示例將返回 arrayOne 中的元素。 如果您需要具有新值的元素,您可以在 function 中反轉 arrayOne 和 arrayTwo。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.